Skip to content

Instantly share code, notes, and snippets.

@Per48edjes
Created November 29, 2022 19:51
Show Gist options
  • Save Per48edjes/b95554a616d1408fab3eb52b5158bd9f to your computer and use it in GitHub Desktop.
Save Per48edjes/b95554a616d1408fab3eb52b5158bd9f to your computer and use it in GitHub Desktop.
LeetCode 206. Reverse Linked List
from typing import Optional
"""
LeetCode 206. Reverse Linked List
"""
class ListNode:
def __init__(self, val, next=None):
self.val = val
self.next = next
# O(n) time complexity, O(1) space complexity
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev, current = None, head
while current:
tmp = current.next
current.next = prev
prev = current
current = tmp
return prev
# O(n) time complexity, O(n) space complexity (similar to optimal recursive approach)
def reverseList2(head: Optional[ListNode]) -> Optional[ListNode]:
node_stack = []
def list_reverser(head: Optional[ListNode]) -> Optional[ListNode]:
while head:
node_stack.append(head)
head = head.next
head = tail = None
while node_stack:
if not head:
head = tail = node_stack.pop()
else:
tail.next = node_stack.pop()
tail.next.next = None
tail = tail.next
return head
return list_reverser(head)
# O(n^2) time complexity, O(n) space complexity
def reverseList3(head: Optional[ListNode]) -> Optional[ListNode]:
def node_append(new_head: Optional[ListNode], node: ListNode) -> Optional[ListNode]:
current, node.next = new_head, None
while current:
if current.next is None:
current.next = node
return new_head
current = current.next
def list_reverser(head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return
if head.next is None:
return head
return node_append(list_reverser(head.next), head)
return list_reverser(head)
@Per48edjes
Copy link
Author

reverseList3 can be optimized to $O(n)$ time complexity by just keeping pointer to the tail + updating tail upon append rather than using node_append to traverse the newly formed list each time to do an append.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment