Link: https://leetcode.com/problems/reverse-linked-list/
Constraints:
The number of nodes in the list is the range [0, 5000].
-5000 <= Node.val <= 5000
Idea
Using a dummy head could make things easier.
For each node in the list:
Set node as dummy's successer
Set dummy's successor to this node
Code
- Iterative solution:
class Solution {
public ListNode reverseList(ListNode head) {
ListNode dummy = new ListNode(0);
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = dummy.next;
dummy.next = cur;
cur = next;
}
return dummy.next;
}
}
- Time: O(n) as we have to traverse all the nodes in the linked list.
- Space: O(1) as we use a dummy node as the fake head of the reversed list.
- Recursive solution
class Solution {
public ListNode reverseList(ListNode head) {
ListNode dummy = new ListNode(0);
reverse(head, dummy);
return dummy.next;
}
private void reverse(ListNode head, ListNode dummy) {
if (head == null) {
return;
}
ListNode next = head.next;
head.next = dummy.next;
dummy.next = head;
reverse(next, dummy);
}
}
- Time: O(n) as we have to traverse all the nodes in the linked list.
- Space: O(n) as the recursive method will invoked against each node in the list.
Similar question: