206. Reverse Linked List*
https://leetcode.com/problems/reverse-linked-list/
Title Description
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?
C ++ implementation 1
Flip the list is very classic problem, iterative approach needs to heart.
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head) return nullptr;
ListNode *prev = nullptr;
while (head) {
auto tmp = head->next;
head->next = prev;
prev = head;
head = tmp;
}
return prev;
}
};
2 in C ++
Recursive method.
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !head->next) return head;
auto tmp = head->next;
auto new_head = reverseList(head->next);
tmp->next = head;
head->next = nullptr;
return new_head;
}
};