反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
使用迭代方法,代码如下:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * struct ListNode *next; 6 * }; 7 */ 8 struct ListNode* reverseList(struct ListNode* head){ 9 if (head == NULL || head->next == NULL) 10 return head; 11 12 struct ListNode *pre = head; 13 struct ListNode *cur = head->next; 14 struct ListNode *tmp = head->next->next; 15 16 while(cur) 17 { 18 tmp = cur->next; 19 cur->next = pre; 20 pre = cur; 21 cur = tmp; 22 } 23 head->next = NULL; 24 25 return pre; 26 27 }
递归方法如下:
1 struct ListNode* reverseList(struct ListNode* head){ 2 if (head == NULL || head->next == NULL) 3 return head; 4 else 5 { 6 struct ListNode *newhead = reverseList(head->next); 7 head->next->next = head; 8 head->next = NULL; 9 return newhead; 10 11 } 12 }
原文:https://www.cnblogs.com/ghwxxg/p/14347402.html