-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpyliststack.py
More file actions
executable file
·73 lines (56 loc) · 1.97 KB
/
pyliststack.py
File metadata and controls
executable file
·73 lines (56 loc) · 1.97 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
__author__ = "streethacker"
#/usr/bin/python
#-*- coding:utf-8 -*-
# Data Structures and Algorithms Using Python
# CHAPTER 7: Stacks
# Listing 7.1: pyliststack.py
class Stack(object):
"""
Implementation of Stack ADT based on Py's list.
For the most efficient ordering, we let the end of the list represent the top of the stack and the front
represent the base.As the stack grows,items are appended to the end of the list and when items are poppe
d,they are removed from the same end.
"""
def __init__(self):
self._stackItems = list()
def __len__(self):
return len(self._stackItems)
def isEmpty(self):
return True if len(self) == 0 else False
def peek(self):
"""
Returns a reference to the item on top of a non-emtpy stack without removing it.
Peeking, which cannot be done on an empty stack,does not modify the stack conten
ts.
"""
assert len(self) > 0, "Cannot peek at empty stack."
return self._stackItems[-1]
def pop(self):
"""
Removes and returns the top item of the stack, if the stack is not empty. Items cannot
be popped from an empty stack. The next item on the stack becomes the new top item.
"""
assert len(self) > 0, "Cannot pop at empty stack."
return self._stackItems.pop()
def push(self, item):
"""
Adds the given item to the top of the stack.
"""
return self._stackItems.append(item)
def printStack(self):
print "The snapshot of the items in the stack:"
for item in self._stackItems:
print item,
print
if __name__ == "__main__":
stack = Stack()
for i in range(10):
stack.push(i)
if not stack.isEmpty():
stack.printStack()
for i in range(5):
stack.pop()
if not stack.isEmpty():
stack.printStack()
topVal = stack.peek()
print "The top value of the stack right now is:", topVal