206. Reverse Linked List

Overview
Just to the topic, we need to revere the input linked list.
Solution 1: iteration
Algorithm

-
initialize
current
tohead
andprevious
toNone
-
Iterate through the linked list:
- Set
next
tocurrent.next
.
We need to savecurrent.next
for removing pointers. - Set
current.next
toprevious
to reverse the link. - Set
previous
tocurrent
to move pointer for the next loop. - Set
current
tonext
to move pointer for the next loop.
- Set
Implement
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: current = head previous = None while current: next = current.next current.next = previous previous, current = current, next return previous

Actually, we don't need current
and next
can also achieve the pointers moving.
class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: previous = None while head: head.next, previous, head = previous, head, head.next return previous
Complexity Analysis
Time complexity: O(n)
Iterating through the linked list takes O(n).
Space complexity: O(1)
Addition variables are constraint that won't grow up with the input, taking O(1).
Solution 2: recursive
Algorithm
-
If
head
is None, it shows that recursive has ended, returningprevious
. -
Set
next
tohead.next
.
We need to savehead.next
to pass it as recursive head. -
Set
head.next
toprevious
to reverse the link. -
Recursively call
next
ashead
andhead
asprevious
.
Implement
class Solution: def reverseList( self, head: Optional[ListNode], previous=None, ) -> Optional[ListNode]: if not head: return previous next = head.next head.next = previous return self.reverseList(next, head)
Complexity Analysis
Time complexity: O(n)
The recursive function will traverse each node, taking O(n) time.
Space complexity: O(n)
The recursive stack needs to store each node and recursively call the next node.
Since we don't employ any optimization techniques, the space complexity is O(n).