码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Reverse Linked List

时间:2015-05-06 20:56:52      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

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

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 };

 

LeetCode Reverse Linked List

标签:

原文地址:http://www.cnblogs.com/lailailai/p/4482965.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!