-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsert_into_linkedlist.py
55 lines (44 loc) · 1.27 KB
/
insert_into_linkedlist.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
class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.nextval = None
class SLinkedList:
def __init__(self):
self.headval = None
self.tailval = None
def insert_at_beginning(self,data):
nb = Node(data)
nb.nextval = self.headval
self.headval=nb
def listprint(self):
printval = self.headval
while printval is not None:
print (printval.dataval)
printval = printval.nextval
def insert_at_end(self,data):
ne= Node(data)
temp = self.headval
while temp.nextval:
temp= temp.nextval
temp.nextval = ne
def insert_position(self,pos,data):
np = Node(data)
temp = self.headval
for i in range(0,pos-1):
temp = temp.nextval
np.data= data
np.nextval = temp.nextval
temp.nextval = np
list = SLinkedList()
list.headval = Node("Mon")
e2 = Node("Tue")
e3 = Node("Wed")
# Link first Node to second node
list.headval.nextval = e2
# Link second Node to third node
e2.nextval = e3
list.insert_at_beginning(10)
list.insert_at_end(20)
list.insert_position(5,15)
list.insert_at_end(40)
list.listprint()