自定义链表实现栈的数据结构,代码如下:
class Stack:
def __init__(self):
self._first = None
def push(self,item):
self._first = _Node(item,self._first)
def pop(self):
self._first = self._first.next
def isEmpty(self):
return self._first is None
class _Node:
def __init__(self,item,next):
self.item = item
self.next = next def main():
stack = Stack()
stack.push("a")
stack.push("b")
stack.push("c")
print(stack._first.item)
print(stack._first.next.item)
print(stack._first.next.next.item) if __name__ == "__main__": main()
运行结果:
>> c
>> b
>> a
栈代码的关键在于实现节点的递归结构
队列是排队买票,先进的先出;栈是挤地铁,先进的反而后出
链表的实现,关键在于一个单位内存空间,既可以存储内容,也可以存储地址(指针)