编写一个函数,实现顺序表的就地逆置,也就是说利用原表的存储空间将顺序表(a1,a2...an)逆置为(an,an-1...a2,a1)。
让我们能想到的是,利用使用三个指针,分别指向开始,中间,结束。元素。通过中间元素实现,开始元素和结束元素的交换,然后,开始元素的指针加一,结束元素的指针减一,这样循环下去,当开始元素的指针不小于中间元素指针时停止。
代码如下:
- #include <stdio.h>
-
#include <stdlib.h>
-
-
typedef struct{
-
int *base;
-
int length;
-
} sqlist;
-
-
void reverseSQ(sqlist *l)
-
{
-
int low = 0, high = l->length - 1;
-
int buf, i, count = l->length / 2;
-
for(i=0; i<count; i++){
-
buf = l->base[low];
-
l->base[low++] = l->base[high];
-
l->base[high--] = buf;
-
}
-
}
-
-
void printSQ(sqlist *l)
-
{
-
int i = 0;
-
for(i=0; i<l->length; i++)
-
printf("%d ",l->base[i]);
-
printf("\n");
-
}
-
-
int main(int argc, char *argv[])
-
{
-
sqlist l;
-
int a,i = 0;
-
int cnt = 0;
-
-
printf("please input count num:");
-
scanf("%d",&cnt);
-
l.base = (int *)malloc(sizeof(int) * cnt);
-
l.length = 0;
-
-
while(i < cnt){
-
scanf("%d",&a);
-
l.base[i++] = a;
-
l.length++;
-
}
-
printf("the contents of the sqlist are\n");
-
printSQ(&l);
-
reverseSQ(&l);
-
printf("the contents of the reversed sqlist are\n");
-
printSQ(&l);
-
free(l.base); //释放内存
-
return 0;
-
}
运行结果:
peng@ubuntu:~/src/test/c/suanfa/miaoqu$ gcc -Wall 7.1-1.c
peng@ubuntu:~/src/test/c/suanfa/miaoqu$ ./a.out
please input count num:5
1 2 3 4 5
the contents of the sqlist are
1 2 3 4 5
the contents of the reversed sqlist are
5 4 3 2 1
阅读(12900) | 评论(0) | 转发(1) |