-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedstack.py
More file actions
87 lines (58 loc) · 2.22 KB
/
linkedstack.py
File metadata and controls
87 lines (58 loc) · 2.22 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
76
77
78
79
80
81
82
83
84
85
86
#-----------------------------------------------------------------------
# linkedstack.py
#-----------------------------------------------------------------------
import stdio
# A Stack object is a last-in-first-out collection.
class Stack:
#-------------------------------------------------------------------
# Construct an empty Stack object.
def __init__(self):
self._first = None # Reference to first _Node
#-------------------------------------------------------------------
# Return True if Stack object self is empty, and False otherwise.
def isEmpty(self):
return self._first is None
#-------------------------------------------------------------------
# Push item onto the top of 'self'.
def push(self, item):
self._first = _Node(item, self._first)
#-------------------------------------------------------------------
# Pop the top item from 'self' and return it.
def pop(self):
item = self._first.item
self._first = self._first.next
return item
#-------------------------------------------------------------------
# Return a string representation of 'self'.
def __str__(self):
s = ''
cur = self._first
while cur is not None:
s += str(cur.item) + ' '
cur = cur.next
return s
#-----------------------------------------------------------------------
# A _Node object references an item and a next _Node object.
# A Stack object is composed of _Node objects.
class _Node:
def __init__(self, item, next):
self.item = item # Reference to an item.
self.next = next # Reference to the next _Node object
#-----------------------------------------------------------------------
# For testing:
def main():
stack = Stack()
while not stdio.isEmpty():
item = stdio.readString()
if item != '-':
stack.push(item)
else:
stdio.write(stack.pop() + ' ')
stdio.writeln()
if __name__ == '__main__':
main()
#-----------------------------------------------------------------------
# more tobe.txt
# to be or not to - be - - that - - - is
# python linkedstack.py < tobe.txt
# to be not that or be