自定义链表实现栈的数据结构,代码如下:
1 class Stack: 2 def __init__(self): 3 self._first = None 4 def push(self,item): 5 self._first = _Node(item,self._first) 6 def pop(self): 7 self._first = self._first.next 8 def isEmpty(self): 9 return self._first is None 10 class _Node: 11 def __init__(self,item,next): 12 self.item = item 13 self.next = next 14 15 def main(): 16 stack = Stack() 17 stack.push("a") 18 stack.push("b") 19 stack.push("c") 20 print(stack._first.item) 21 print(stack._first.next.item) 22 print(stack._first.next.next.item) 23 24 if __name__ == "__main__": main()
运行结果:
>> c
>> b
>> a
栈代码的关键在于实现节点的递归结构
队列是排队买票,先进的先出;栈是挤地铁,先进的反而后出
链表的实现,关键在于一个单位内存空间,既可以存储内容,也可以存储地址(指针)