链表逆置
代码:
1 #include "stdafx.h" 2 #include "assert.h" 3 4 typedef int DataType; 5 6 struct node 7 { 8 DataType data; 9 node * next; 10 }; 11 12 node * create_list(int a[], int n) 13 { 14 if (n <= 0) 15 return NULL; 16 node * first = new node; 17 first->data = a[0]; 18 first->next = NULL; 19 node *cur = first; 20 for (int i=1;i<n;i++) 21 { 22 node * next = new node; 23 next->data = a[i]; 24 next->next = NULL; 25 cur->next = next; 26 cur = next; 27 } 28 return first; 29 } 30 31 void printf_list(node *head) 32 { 33 while(head) 34 { 35 printf("%d ", head->data); 36 head = head->next; 37 } 38 printf("\n"); 39 } 40 41 node * reserve_list(node *head) 42 { 43 //assert(head != NULL); 44 if(head == NULL) //不管是笔试还是面试,这些细节都是考察要点!!! 45 return head; 46 node *pre = head, *post = head->next; 47 while(post) 48 { 49 node * temp = post->next; 50 post->next = pre; 51 pre = post; 52 post = temp; 53 } 54 head->next = NULL; 55 return pre; 56 } 57 58 node * recursion_reserve(node *head) //递归(也可以使用二级指针将newHead带出递归) 59 { 60 if (head == NULL) 61 return NULL; 62 63 if (head->next == NULL) 64 return head; 65 66 node * pre = head, * post = head->next; 67 68 if(post->next == NULL) 69 { 70 post->next = pre; 71 pre->next = NULL; //去掉这句,当链表元素个数为2时,死循环。 72 return post; 73 } 74 else 75 { 76 node * newHead = recursion_reserve(post); 77 post->next = pre; 78 pre->next = NULL; 79 return newHead; 80 } 81 } 82 83 int _tmain(int argc, _TCHAR* argv[]) 84 { 85 int a[] = {1,2,3,4,5,6,7,8,9}; 86 87 node * head = create_list(a, sizeof(a)/sizeof(int)); 88 printf_list(head); 89 90 node *reservedHead = reserve_list(head); //reserve_list(NULL) 91 printf_list(reservedHead); 92 93 node *recursionHead = recursion_reserve(reservedHead); 94 printf_list(recursionHead); 95 96 getchar(); 97 return 0; 98 }