-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstack.py
More file actions
70 lines (58 loc) · 1.46 KB
/
Copy pathstack.py
File metadata and controls
70 lines (58 loc) · 1.46 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
class NodeStructure:
def __init__(self, value, tail=None):
self.value = value
self.next = tail
class Stack:
def __init__(self, *start):
self.head = None
for node in start:
self.prepend(node)
def prepend(self, value):
# add from the top
self.head = NodeStructure(value, self.head)
def pop(self):
if self.head is None:
raise Exception("Stack is empty ")
val = self.head.value
self.head = self.head.next
return val
def remove(self, value):
# to remove any item from the stack
n = self.head
last = None
while n is not None:
if n.value == value:
if last is None:
self.head = self.head.next
else:
last.next = n.next
return True
last = n
n = n.next
return False
def __iter__(self):
n = self.head
while n is not None:
yield n.value
n = n.next
def __repr__(self):
if self.head is None:
return "Stack: [] "
return "Stack:[ {0:s} ]".format(",".join((map(str, self))))
def main():
s = Stack()
s.prepend(10)
s.prepend(20)
s.prepend(30)
s.prepend(40)
print(s)
s.pop()
print(s)
s.prepend(40)
print(s)
s.remove(40)
print(s)
s.remove(20)
print(s)
if __name__ == '__main__':
main()