您的位置:首页 > 其它

[leetcode] 206. Reverse Linked List

2016-06-01 11:35 351 查看
Reverse a singly linked list.

Solution 1

Idea: create a dummy node and insert node after dummy node 

* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head==NULL)
return head;

ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* cur = head;
while(cur->next){
ListNode* tmp = cur->next;
cur->next = tmp->next;
tmp->next = dummy->next;
dummy->next = tmp;
}
return dummy->next;

}
};


Solution 2

Idea: iteratively reverse two nodes

* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head) return head;
ListNode* pre = NULL;
ListNode* cur = head;
while (cur&&cur->next){
ListNode* tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
cur->next = pre;
return cur;
}
};


Solution 3

Idea: recursive function

* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head||!(head->next)) return head;
ListNode* node = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return node;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode easy