-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseLinkedList_Day41.py
More file actions
51 lines (40 loc) · 1.2 KB
/
Copy pathReverseLinkedList_Day41.py
File metadata and controls
51 lines (40 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#Brute Approach
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return None
nodes = []
curr = head
while curr:
nodes.append(curr)
curr = curr.next
for i in range(len(nodes) - 1, 0, -1):
nodes[i].next = nodes[i - 1]
nodes[0].next = None
return nodes[-1]
# Time Complexity: O(N)
# Space Complexity: O(N) (for storing nodes)
#Better Approach
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
newHead = self.reverseList(head.next)
head.next.next = head
head.next = None
return newHead
# Time Complexity: O(N)
# Space Complexity: O(N) (due to recurssion call stack)
#Optimal Approach
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
curr = head
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prev
# Time Complexity: O(N)
# Space Complexity: O(1) (in-place)