leetcode 206. Reverse Linked List
2016-10-06 14:40
423 查看
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?
递归:
/**
* 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 || head->next == NULL) return head;
ListNode* newhead = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return newhead;
}
};
循环:
/**
* 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 || head->next == NULL) return head;
ListNode* newhead = NULL;
ListNode* p = head;
while(p){
ListNode* tmp = p;
p = p->next;
tmp->next = newhead;
newhead = tmp;
}
return newhead;
}
};
click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
递归:
/**
* 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 || head->next == NULL) return head;
ListNode* newhead = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return newhead;
}
};
循环:
/**
* 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 || head->next == NULL) return head;
ListNode* newhead = NULL;
ListNode* p = head;
while(p){
ListNode* tmp = p;
p = p->next;
tmp->next = newhead;
newhead = tmp;
}
return newhead;
}
};
相关文章推荐
- 【leetcode】206.Reverse Linked List
- LeetCode-206. Reverse Linked List
- LeetCode-206. Reverse Linked List
- 【LeetCode】206. Reverse Linked List
- 【leetcode】206. Reverse Linked List My Submissions Question
- [leetcode]206. Reverse Linked List
- 206. Reverse Linked List leetcode list
- Leetcode-206. Reverse Linked List
- LeetCode 206. Reverse Linked List
- LeetCode 206. Reverse Linked List
- [LeetCode] 206. Reverse Linked List
- LeetCode 206. Reverse Linked List
- LeetCode 206. Reverse Linked List
- 【LeetCode】206. Reverse Linked List
- [LeetCode]206. Reverse Linked List&92. Reverse Linked List II
- Leetcode 206. Reverse Linked List
- LeetCode:206. Reverse Linked List
- Leetcode题解 206. Reverse Linked List
- Leetcode 206. Reverse Linked List
- Leetcode206. Reverse Linked List