-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.py
More file actions
75 lines (62 loc) · 1.67 KB
/
Copy pathstack.py
File metadata and controls
75 lines (62 loc) · 1.67 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
"""
stack.py
author: James heliotis
description: A linked stack (LIFO) implementation
"""
from node import LinkedNode
class Stack:
__slots__ = "top"
def __init__( self ):
""" Create a new empty stack.
"""
self.top = None
def __str__( self ):
""" Return a string representation of the contents of
this stack, top value first.
"""
result = "Stack["
n = self.top
while n != None:
result += " " + str( n.value )
n = n.link
result += " ]"
return result
def is_empty( self ):
return self.top == None
def push( self, newValue ):
self.top = LinkedNode( newValue, self.top )
def pop( self ):
assert not self.is_empty(), "Pop from empty stack"
self.top = self.top.link
def peek( self ):
assert not self.is_empty(), "peek on empty stack"
return self.top.value
insert = push
remove = pop
def test():
s = Stack()
print( s )
for value in 1, 2, 3:
s.push( value )
print( s )
print( "Popping:", s.peek() )
s.pop()
print( s )
for value in 15, 16:
s.insert( value )
print( s )
print( "Removing:", s.peek() )
s.remove()
print( s )
while not s.is_empty():
print( "Popping:", s.peek() )
s.pop()
print( s )
print( "Trying one too many pops... ", end="" )
try:
s.pop()
print( "Problem: it succeeded!" )
except Exception as e:
print( "Exception was '" + str( e ) + "'" )
if __name__ == "__main__":
test()