-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathlinked_list.py
More file actions
115 lines (89 loc) · 2.72 KB
/
linked_list.py
File metadata and controls
115 lines (89 loc) · 2.72 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import matplotlib.pyplot as plt
#THe first class represents a single node in the linked list
class Node:
def __init__(self, data):
self.data = data
self.next = None
#The second class represents entire linked list and contains the "head" of code
class Linkedlist:
def __init__(self):
self.head = None
def create_node(self, data):
new_node = Node(data)
return new_node
def connect_node(self, node1, node2):
node1.next = node2
def add_node(self, data):
new_node = self.create_node(data)
if not self.head:
self.head = new_node
return
current = self.head
while current.next:
current = current.next
current.next = new_node
def insert_node(self, data, position):
new_node = self.create_node(data)
if position == 0:
new_node.next = self.head
self.head = new_node
return
current = self.head
for i in range(position-1):
if not current:
raise IndexError("Position out of range")
current = current.next
new_node.next = current.next
current.next = new_node
def delete_node(self, data):
if not self.head:
raise ValueError("List is empty")
if self.head.data == data:
self.head = self.head.next
return
current = self.head
while current.next:
if current.next.data == data:
current.next = current.next.next
return
current = current.next
raise ValueError("Value not found in the list")
def graph(self):
nodes = []
current = self.head
i = 0
while current:
nodes.append((i, current.data))
current = current.next
i += 1
x = [node[0] for node in nodes]
y = [node[1] for node in nodes]
plt.plot(x, y)
plt.xlabel("Node Index")
plt.ylabel("Node Value")
plt.title("Linked List Graph")
plt.show()
ll = Linkedlist()
ll.add_node(1)
ll.add_node(2)
ll.add_node(3)
print('Linked list: ')
current = ll.head
while current:
print(current.data)
current = current.next
ll.insert_node(0, 0)
ll.insert_node(4, 4)
print('Linked list after inserting datas')
current = ll.head
while current:
print(current.data)
current = current.next
ll.delete_node(0)
ll.delete_node(4)
print('Linked list after deleting datas')
current = ll.head
while current:
print(current.data)
current = current.next
ll.graph()