-
Notifications
You must be signed in to change notification settings - Fork 0
/
073.py
51 lines (40 loc) · 962 Bytes
/
073.py
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
"""
Problem:
Given the head of a singly linked list, reverse it in-place.
"""
from DataStructures.LinkedList import LinkedList
def reverse_inplace(ll: LinkedList) -> None:
ll.rear = ll.head
ptr_prev, ptr_curr, ptr_next = None, ll.head, ll.head.next
# reversing the flow
while ptr_curr is not None:
ptr_curr.next = ptr_prev
ptr_prev, ptr_curr = ptr_curr, ptr_next
if ptr_next is None:
break
ptr_next = ptr_next.next
ll.head = ptr_prev
if __name__ == "__main__":
ll = LinkedList()
for num in range(1, 6):
ll.add(num)
print(ll)
reverse_inplace(ll)
print(ll)
ll = LinkedList()
for num in range(1, 3):
ll.add(num)
print(ll)
reverse_inplace(ll)
print(ll)
ll = LinkedList()
for num in range(1, 2):
ll.add(num)
print(ll)
reverse_inplace(ll)
print(ll)
"""
SPECS:
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(1)
"""