Reverse a Linked List
Problem
Reverse a singly linked list.
Thought Process
To reverse a LinkedList, we need to reverse one node at a time. We will start with a variable
currentwhich will initially point to the head of the LinkedList and a variablepreviouswhich will point to the previous node that we have processed; initiallypreviouswill point tonull.In a stepwise manner, we will reverse the
currentnode by pointing it to thepreviousbefore moving on to the next node. Also, we will update thepreviousto always point to the previous node that we have processed.
Solution
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
current, previous, nextP = head, None, None
while current:
nextP = current.next
current.next = previous
previous = current
current = nextP
return previous
#Time: O(n)
#Space: O(1)Last updated
Was this helpful?