-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path73_Google_Reverse_Singly_Linked_List.py
More file actions
executable file
·53 lines (37 loc) · 1.07 KB
/
73_Google_Reverse_Singly_Linked_List.py
File metadata and controls
executable file
·53 lines (37 loc) · 1.07 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
52
53
"""
This problem was asked by Google.
Given the head of a singly linked list, reverse it in-place.
"""
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def __repr__(self):
return "{}->{}".format(self.data, self.next)
def reverse_ll(head):
prev_node = None
curr_node = head
next_node = head.next
while next_node:
curr_node.next = prev_node
prev_node = curr_node
curr_node = next_node
next_node = curr_node.next
curr_node.next = prev_node
return curr_node
def print_ll(head):
curr = head
while curr:
print(curr.data, end=' ')
curr = curr.next
print()
if __name__ == '__main__':
# 1->2->3->4->5
linked_list = Node(data=1, next=Node(data=2, next=Node(data=3, next=Node(data=4, next=Node(5)))))
print("linked list before reversal:")
# print_ll(linked_list)
print(linked_list)
print("linked list after reversal:")
linked_list = reverse_ll(linked_list)
# print_ll(linked_list)
print(linked_list)