目录
【堆栈】
-
顺序栈
实现和操作。
注:和线性表的区别只在于数据输入和输出的位置是固定的。
import ctypes
#顺序栈
class Stack():
def __init__(self):
self._capacity = 10
self._top = 0
self._A = self._make_array(self._capacity)
def isEmpty(self):
return self._top == 0
def push(self,value):
if self._top == self._capacity:
self._resize(self._capacity*2)
self._A[self._top] = value
self._top += 1
def pop(self):
if self.isEmpty():
raise Exception("no value")
else:
# value = self._A[self._top]
self._top -= 1
# return value
def clear(self):
while self._top:
self.pop()
def _make_array(self, c):
return (c* ctypes.py_object)()
def _resize(self, c):
B = self._make_array(c)
for i in range(self._top):
B[i] = self._A[i]
self._A = B
self._capacity = c
def _print(self):
for i in range(self._top):
print self._A[i],' ',
print ''
测试:
mystack = Stack()
mystack.push(1)
mystack.push(2)
mystack.push(3)
mystack.push(4)
mystack.push(5)
mystack.push(1)
mystack.push(2)
mystack.push(3)
mystack.push(4)
mystack.push(5)
mystack.push(1)
mystack.push(2)
mystack.push(3)
mystack.push(4)
mystack.push(5)
mystack._print()
mystack.pop()
mystack._print()
mystack.pop()
mystack._print()
mystack.pop()
mystack._print()
mystack.clear()
mystack._print()
-
链栈
实现和操作。
#先定一个node的类
class Node(): #value + next
def __init__ (self, value = None, next = None):
self._value = value
self._next = next
def getValue(self):
return self._value
def getNext(self):
return self._next
def setValue(self,new_value):
self._value = new_value
def setNext(self,new_next):
self._next = new_next
#链栈
class LinkStack():
def __init__(self):
self._count = 0
self._top = None
def isEmpty(self):
return top == None
def push(self,value):
new_node = Node(value,self._top)
self._top = new_node
self._count += 1
def pop(self):
last = self._top
self._top = self._top.getNext()
self._count -= 1
last.next