-
Notifications
You must be signed in to change notification settings - Fork 226
/
Copy pathstack.py
129 lines (86 loc) · 2.59 KB
/
stack.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
from contextlib import nullcontext
class Node:
def __init__(self,value=None):
self.value=value
self.next=None
class SlinkedList:
def __init__(self):
self.head=None
self.tail=None
def __iter__(self):
node=self.head
while node:
yield node
node=node.next
def insert(self,value,location):
Newnode=Node(value)
if self.head==None:
self.tail=Newnode
self.head=Newnode
elif location==0:
Newnode.next=self.head
self.head=Newnode
elif location ==-1:
Newnode.next=None
self.tail.next=Newnode
self.tail=Newnode
else:
temp=self.head
index=0
while index < location-1:
temp=temp.next
index+=1
Nextnode=temp.next
temp.next=Newnode
Newnode.next=Nextnode
if temp==self.tail:
self.tail=Newnode
def transverse(self):
node=self.head
while node is not None:
print(node.value)
node=node.next
def search(self,val):
node=self.head
while node is not None:
if node.value==val:
print("yeet")
node=node.next
def delete(self,location):
if location==0:
if self.head==self.tail:
self.head=None
self.tail=None
else:
self.head=self.head.next
elif location==-1:
if self.head==self.tail:
self.head=None
self.tail=None
else:
node=self.head
while node is not None:
if node.next==self.tail:
break
node=node.next
node.next=None
self.tail=node
else:
temp=self.head
index=1
# here we have taken one location back of the current node
while index<location-1:
temp=temp.next
index+=1
nextnode=temp.next
temp.next=nextnode.next
singleLinkedList=SlinkedList()
singleLinkedList.insert(1,1)
singleLinkedList.insert(2,-1)
singleLinkedList.insert(3,-1)
singleLinkedList.insert(4,-1)
print([i.value for i in singleLinkedList])
singleLinkedList.transverse()
singleLinkedList.search(2)
singleLinkedList.delete(3)
print([i.value for i in singleLinkedList])