/*** reverse.c ***/ #include<stdio.h> #include<stdlib.h> struct list { int data; struct list *next; }; struct list *create_list() { return calloc(sizeof(struct list),1); } struct list *insert_list(struct list *ls,int n,int data) { struct list *p = ls; while(p && n--) { p = p->next; } if(NULL == p) { return NULL; } struct list *node = create_list(); node->data = data; node->next = p->next; p->next = node; return node; } void traverse(struct list *ls) { struct list *p = ls; while(p) { printf("%d ",p->data); p = p->next; } } void reverse(struct list *ls) { if(ls->next == NULL) { return; } if(ls->next->next == NULL) { return; } struct list *last = ls->next; struct list *pre = ls; struct list *cur = ls; struct list *next = NULL; while(cur) { next = cur->next; cur->next = pre; pre = cur; cur = next; } ls->next = pre; last->next = NULL; } int main() { struct list *first = create_list(); int i; for(i = 0; i < 10; i++) { insert_list(first,0,i); } traverse(first); reverse(first); printf("reverse "); traverse(first); return 0; }
运行结果:
ubuntu1604@ubuntu:~/wangqinghe/C/20190730$ gcc reverse.c -o reverse
ubuntu1604@ubuntu:~/wangqinghe/C/20190730$ ./reverse
0
9
8
7
6
5
4
3
2
1
0
reverse
0
0
1
2
3
4
5
6
7
8
9
问题:创建链表时多了一个0,存疑