Python: Stack class

 1 class Stack():
 2     def __init__(self, size):
 3         self.stack = []
 4         self.size = size
 5         self.top = -1
 6 
 7     def push(self, content):
 8         if self.isFull():
 9             print "Stack is full"
10         else:
11             self.stack.append(content)
12             self.top += 1
13 
14     def pop(self):
15         if self.isEmpty():
16             print "Stack is empty"
17         else:
18             self.stack.pop()
19             self.top -= 1
20 
21     def isFull(self):
22         if self.top + 1 == self.size:
23             return True
24         else:
25             return False
26 
27     def isEmpty(self):
28         if self.top == -1:
29             return True
30         else:
31             return False
32 
33 def printStackInfo(aStack):
34     print "isEmpty:\t{0}".format(aStack.isEmpty())
35     print "isFull:\t\t{0}".format(aStack.isFull())
36     print "top:\t\t{0}".format(aStack.top)
37     print "stack:\t\t{0}".format(aStack.stack)
38 
39 print "1. Initialise a stack with a size of 2, i.e. store at most 2 elements"
40 s = Stack(2)
41 printStackInfo(s)
42 
43 print "\n2. Push 'a'"
44 s.push('a')
45 printStackInfo(s)
46 
47 print "\n3. push 'b'"
48 s.push('b')
49 printStackInfo(s)
50 
51 print "\n4. push 'c'"
52 s.push('c')
53 printStackInfo(s)
54 
55 print "\n5. pop the top element"
56 s.pop()
57 printStackInfo(s)
58 
59 print "\n6. pop the top element"
60 s.pop()
61 printStackInfo(s)
62 
63 print "\n7. pop the top element"
64 s.pop()
65 printStackInfo(s)

 

posted @ 2015-07-09 08:52  兔纸不吃草  阅读(694)  评论(0编辑  收藏  举报