class LNode(object):
def __init__(self,elem,next=None):
self.elem = elem
self.next = next
class LStack(LNode):
def __init__(self):
self._top = None
def is_empty(self):
return self._top is None
#打印栈顶元素
def top(self):
#头指针空,即没有元素
if self._top is None:
print("in LStack.top()")
#否则返回第一个元素
return self._top.elem
def push(self,elem):
self._top = LNode(elem,self._top)
def pop(self):
if self._top is None:
print("in LStack.pop()")
p = self._top
self._top = p.next
return p.elem
stack = LStack()
list1 = ['a','b','c','d','e']
list2 = []
# for i in list1:
# stack.push(i)
while not stack.is_empty():
list2.append(stack.pop())
print("进栈前顺序:",list1)
print("出栈后顺序:",list2)
# print(stack.top())
输出结果
进栈前顺序: ['a', 'b', 'c', 'd', 'e']
出栈后顺序: ['e', 'd', 'c', 'b', 'a']