1.基于python列表(可变数组)实现栈
使用列表实现栈特点为使用的空间与栈个数成线性相关,且进出栈操作运行时间为常量
class Stack:
def __init__(self):
self.value = []
def push(self, item):
self.value.append(item)
def pop(self):
if self.is_empty():
print('为空栈!')
return
return self.value.pop()
def is_empty(self):
return self.len() == 0
def len(self):
return len(self.value)
def peek(self):
if self.is_empty():
print('为空栈!')
return
# return self.value[self.len()-1]
return self.value[-1]
2.基于链表实现栈
链表为一个递归数据结构
class ListNode:
def __init__(self, item, next = None):
self.item = item
self.next = next
class ListStack():
def __init__(self):
self.top = None
def is_empty(self):
return self.top is None
def push(self, item):
self.top = ListNode(item, self.top)
def top(self):
if self.top is None:
print("空栈")
return
return self.top.item
def pop(self):
if self.top is None:
print("空栈")
return
t = self.top
self.top = self.top.next
return t.item
if __name__ == '__main__':
st = ListStack()
for i in range(1, 10, 2):
st.push(i)
while not st.is_empty():
print(st.pop())