206. Reverse Linked List
Problem description:
Reverse a singly linked list.
Example:1
2Input: 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?
Solution iterative better:
Use two variables, pre
and cur
. Another local variable to keep the swapping node.1
2
3
4
5
6
7
8
9
10
11
12
13
14class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *pre= NULL, *cur= head;
while(cur){
ListNode* tmp= cur->next;
cur->next= pre;
pre= cur;
cur= tmp;
}
return pre;
}
};
Solution:
Iteratively solution:
Create a dummy node in front of the head
node. Use pre
and cur
to do the swap. But when we do the swapping, we need to use a tmp
node to store the cur
to avoid dropping nodes in between.1
2
3
4dummy-A-B-C-D-E-F
dummy-E-D-C-B-A-F
dummy-F-E-D-C-B-A
1 | /** |
1 | /** |
time complexity: $O(n))$
space complexity: $O(1)$
Recursive solution:
Try to think the end state for recursion. When the recursion reaches to 5
, it would return node 5
to previous recursion. And previous recursion stack would look like this.1
4->5->null
And what we want is to reverse the list, so we could put 4
to the back of 5
.
1 | /** |
1 | /** |
reference:
https://goo.gl/HSqym3