1. 单链表的逆序打印 - 递归
- void print_reverse_list(node* head)
- {
- assert(head);
- if(head->next == NULL)
- printf("%d\n",head->data);//print the last node
- else
- {
- print_reverse_list(head->next);
- printf("%d\n",head->data);//print other nodes.
- }
- }
2. 单链表逆序 - 循环算法
61 LINK_NODE *ReverseLink(LINK_NODE *head) 62 { 63 LINK_NODE *next; 64 LINK_NODE *prev = NULL; 65 66 while(head != NULL) 67 { 68 next = head->next; 69 head->next = prev; 70 prev = head; 71 head = next; 72 } 73 74 return prev; 75 } |
单链表逆序 - 递归实现
77 LINK_NODE *ReverseLink2(LINK_NODE *head)
78 {
79 LINK_NODE *newHead;
80
81 if((head == NULL) || (head->next == NULL))
82 return head;
83
84 newHead = ReverseLink2(head->next); /*递归部分*/
85 head->next->next = head; /*回朔部分*/
86 head->next = NULL;
87
88 return newHead;
89 }