206. Reverse Linked List
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Approch
1.题目很不错,特地记录下来。
Code
1.迭代式
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur = head, *p = nullptr;
while (cur) {
cur = cur->next;
head->next = p;
p = head;
head = cur;
}
return p;
}
};
- 递归式
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == nullptr || head->next == nullptr)return head;
ListNode*p = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return p;
}
};