-
Notifications
You must be signed in to change notification settings - Fork 242
/
Copy pathdouble_linkedlist.py
103 lines (93 loc) · 2.8 KB
/
double_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
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
class Node:
def __init__(self,data):
self.data=data
self.next=None
self.prev=None
class link:
def __init__(self):
self.head=None
def insertBeg(self,newnode):
if(self.head==None):
self.head=newnode
else:
newnode.next=self.head
self.head.prev=newnode
self.head=newnode
def insertEnd(self,newnode):
if(self.head==None):
self.head=newnode
else:
ptr=self.head
while(ptr.next!=None):
ptr=ptr.next
ptr.next=newnode
newnode.prev=ptr
def insertAny(self,newnode,val):
if(self.head==None):
self.head=newnode
else:
ptr=self.head
while(ptr.next!= None and ptr.data!=val):
ptr=ptr.next
newnode.next=ptr.next
newnode.prev=ptr
ptr.next.prev=newnode
ptr.next=newnode
def deleteBeg(self):
strt=self.head
self.head=strt.next
self.head.prev=None
del strt
def deleteEnd(self):
strt=self.head
while(strt.next.next!=None):
strt=strt.next
ptr=strt.next
strt.next=None
del ptr
def deleteAny(self,ele):
strt=self.head
while(strt.next!=None and strt.data!=ele):
strt=strt.next
ptr=strt
strt.prev.next=strt.next
strt.next.prev=strt.prev
del ptr
def print(self):
nodes=self.head
while(nodes!=None):
print(nodes.data)
nodes=nodes.next
n=int(input("Enter the number of nodes:"))
l=link()
for i in range (n):
ele=int(input("enter the element in the list:"))
enter=Node(ele)
choice=int(input("enter 1 to enter at the beginning and 2 to add the end and 3 to enter at any position:"))
match (choice):
case 1:
l.insertBeg(enter)
case 2:
l.insertEnd(enter)
case 3:
bef=int(input("Enter the element after which to be added:"))
l.insertAny(enter,bef)
case _:
print("enter properly")
l.print()
d=int(input("Enter 1 to perform deletion and -1 to stop:"))
while(d!=-1):
choice=int(input("enter 1 to delete at the beginning and 2 to delete the end and 3 to delete from any position:"))
match (choice):
case 1:
l.deleteBeg()
case 2:
l.deleteEnd()
case 3:
bef=int(input("Enter the element to be deleted:"))
l.deleteAny(enter,bef)
case _:
print("enter properly")
d=int(input("Enter 1 to perform deletion and -1 to stop:"))
print("\n")
l.print()