python实现栈

  由于python弱类型,因此免去了写泛型的麻烦。我定义一个stack类以栈的操作来维护一个list。

 1 class stack:
 2     def __init__(self, _size = 1024):
 3         self.data = []
 4         self._size = _size
 5         self._top = -1
 6 
 7     def empty(self):
 8         if self._top == -1:
 9             return True
10         else:
11             return False
12 
13     def size(self):
14         return self._top+1
15 
16     def top(self):
17         return self.data[self._top]
18 
19     def clear(self):
20         self.data = []
21         self._top = -1
22 
23     def push(self, ele):
24         if self._top + 1 == self._size:
25             raise 'Stack Over Flow'
26         else:
27             self.data.append(ele)
28             self._top += 1
29 
30     def pop(self):
31         if self.empty():
32             raise 'Stack Under Flow'
33         else:
34             ele = self.data[self._top]
35             del self.data[self._top]
36             self._top -= 1
37             return ele
38 
39 s = stack(5)
40 
41 s.push(1)
42 s.push(2)
43 s.push(3)
44 s.push(5)
45 s.push(4)
46 # s.push(233)
47 
48 size = s.size()
49 for i in range(0, size):
50     print(s.top())
51     s.pop()

 

posted @ 2015-09-20 01:16  Kirai  阅读(214)  评论(0编辑  收藏  举报