写代码报错改bug真的痛苦╥﹏╥
- 数据结构书p28页:编写程序实现顺序表的逆置
功能函数如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| void Vert(SeqList *L) { int temp;int i; if(L->n%2==0) { for(i=0;i<L->n/2;i++) { temp=L->element[i]; L->element[i]=L->element[L->n-i]; L->element[L->n-i]=temp; } } else { for(i=0;i<(L->n-1)/2;i++) { temp=L->element[i]; L->element[i]=L->element[L->n-i]; L->element[L->n-i]=temp; } } }
|
想半天页没看出来哪里错了,一运行程序就开始死循环。然后问了文心一言。当顺序表元素个数为偶数时,程序运行没问题。当为奇数时,中间的元素 (L->n)/2 作为中心点,在逆置后保留原位。但只循环到 (L->n-1)/2 ,意味着最后一个元素没有交换。这是他的解释,后来我发现其实是我索引出错了,数组索引是从0开始的。中间的数无论是否交换都不变。
以下是一个统一的逆置标准:
1 2 3 4 5 6 7 8 9 10 11
| void Vert(SeqList *L) { int temp; int i; for (i = 0; i < L->n / 2; i++) { temp = L->element[i]; L->element[i] = L->element[L->n - 1 - i]; L->element[L->n - 1 - i] = temp; } }
|