forked from prabhupant/python-ds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linked_list.py
73 lines (53 loc) · 1.47 KB
/
linked_list.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class Node():
def __init__(self, val):
self.val = val
self.next = None
class LinkedList():
def __init__(self):
self.head = None
def print_list(self):
curr = self.head
while curr:
print(curr.val)
curr = curr.next
def insert_front(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def insert_after(self, prev_node, new_data):
if prev_node is None:
print("Previous node is absent!")
return
new_node = Node(new_data)
new_node.next = prev_node.next
prev_node.next = new_node
def insert_end(self, new_data):
if self.head is None:
self.head = Node(new_data)
return
curr = self.head
while curr.next:
curr = curr.next
curr.next = Node(new_data)
def reverse(self):
if self.head is None:
return None
curr = self.head
prev = None
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
self.head = prev
if __name__ == '__main__':
llist = LinkedList()
llist.insert_end(1)
llist.insert_end(2)
llist.insert_end(3)
llist.insert_after(llist.head.next.next, 4)
llist.insert_end(5)
llist.insert_front(0)
llist.print_list()
llist.reverse()
llist.print_list()