philosyang.com

206. Reverse Linked List

Chat I’m so rusty on this.

 1# Definition for singly-linked list.
 2# class ListNode:
 3#     def __init__(self, val=0, next=None):
 4#         self.val = val
 5#         self.next = next
 6class Solution:
 7    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
 8        if not head:
 9            return None
10
11        buffer = deque([])
12        node = head
13
14        while node:
15            buffer.appendleft(node)
16            node = node.next
17
18        # print(buffer)
19
20        head = buffer[0]
21        node = head
22
23        for i, node in enumerate(buffer):
24            if i == len(buffer) - 1:
25                node.next = None
26            else:
27                node.next = buffer[i + 1]
28
29        return head

This version is passing with tc=O(2n), sc=O(n).

The clean, standard iterative approach is O(n), O(1).

 1# Definition for singly-linked list.
 2# class ListNode:
 3#     def __init__(self, val=0, next=None):
 4#         self.val = val
 5#         self.next = next
 6class Solution:
 7    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
 8        prev = None
 9        node = head
10
11        # 1 -> 2 -> 3
12        while node:
13            nxt = node.next     # 2
14            node.next = prev    # 0
15            prev = node         # 1
16            node = nxt          # 2
17        
18        return prev

#Neetcode150 #Linked-List #Python