-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0206-reverse-linked-list.py
More file actions
40 lines (33 loc) · 946 Bytes
/
0206-reverse-linked-list.py
File metadata and controls
40 lines (33 loc) · 946 Bytes
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
# time complexity: O(n)
# space complexity: O(1)
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
curr = head
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev
# time complexity: O(n)
# space complexity: O(n)
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if (not head) or (not head.next):
return head
p = self.reverseList(head.next)
head.next.next = head
head.next = None
return p
root = ListNode(1)
root.next = ListNode(2)
root.next.next = ListNode(3)
root.next.next.next = ListNode(4)
root.next.next.next.next = ListNode(5)
print(Solution().reverseList(root))