0206. Reverse Linked List
Easy | Linked List + Two Pointer | 16 ms (98.94%), 15.4 MB (80.06%)
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Input: head = [1,2]
Output: [2,1]
Input: head = []
Output: []class Solution:
def reverseList(self, head: ListNode) -> ListNode:
# (base case)
if not head: return head
if not head.next: return head
# ==================================================
# Linked List (Iterative) =
# ==================================================
# time : O(n)
# space : O(1)
prev = None
while head:
# STORE next node for next iteration
tmp = head.next
# RE-ASSIGN next pointer to prev node
head.next = prev
# ASSIGN prev node to current node
prev = head
# MOVE current node to next node
head = tmp
return prev
Last updated