Reverse Linked List
Question
Reverse a singly linked list.
Example 1: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Approach 1: Iterative
Intuition and Algorithm
Assume that we have linked list 1 → 2 → 3 → Ø
, we would
like to change it to Ø ← 1 ← 2 ← 3
.
While you are traversing the list, change the current node's next pointer to point to its previous element. Since a node does not have reference to its previous node, you must store its previous element beforehand. You also need another pointer to store the next node before changing the reference. Do not forget to return the new head reference at the end!
1 | # Definition for singly-linked list. |
Complexity Analysis
Time complexity : O(n). Assume that n is the list's length, the time complexity is O(n).
Space complexity : O(1).
Runtime: 28 ms, faster than 99.98% of Python3 online submissions forReverse Linked List.
Memory Usage: 14.5 MB, less than 50.22% of Python3 online submissions for Reverse Linked List.
Approach 2: Recursive
Intuition and Algorithm
The recursive version is slightly trickier and the key is to work
backwards. Assume that the rest of the list had already been reversed,
now how do I reverse the front part? Let's assume the list is:
Assume from node
We want
So,
Be very careful that
1 | class Solution: |
Complexity analysis
Time complexity : O(n). Assume that n is the list's length, the time complexity is O(n).
Space complexity : O(n). The extra space comes from implicit stack space due to recursion. The recursion could go up to n levels deep.
Runtime: 44 ms, faster than 69.21% of Python3 online submissions forReverse Linked List.
Memory Usage: 19.1 MB, less than 11.36% of Python3 online submissions for Reverse Linked List.