LeetCode Reverse Linked List

绝对老题了,感觉已经重复了

Reverse a singly linked list.

click to show more hints.

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?

递归版本

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9  // 19:22
10 class Solution {
11 public:
12     ListNode* reverseList(ListNode* head) {
13         return reverseList(NULL, head);
14     }
15     
16     ListNode* reverseList(ListNode* last, ListNode* head) {
17         if (head == NULL) {
18             return last;
19         }
20         ListNode* rest = head->next;
21         ListNode* nhead = reverseList(head, rest);
22         head->next = last;
23         return nhead;
24     }
25 };

非递归版本

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9  // 19:20
10 class Solution {
11 public:
12     ListNode* reverseList(ListNode* head) {
13         if (head == NULL) {
14             return head;
15         }
16         ListNode* pre = NULL;
17         ListNode* cur = head;
18         while (cur != NULL) {
19             ListNode* tmp = cur->next;
20             cur->next = pre;
21             pre = cur;
22             cur = tmp;
23         }
24         return pre;
25     }
26 };

 

posted @ 2015-05-06 19:37  卖程序的小歪  阅读(151)  评论(0编辑  收藏  举报