且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用链接列表实现堆栈

更新时间:2021-08-10 01:13:06

假设你真的想从头开始而不是使用其中一个非常好的现有堆栈实现然后我建议:

Assuming you genuinely want to do this from scratch rather than using one of the perfectly good existing stack implementations then I would recommend:


  • 创建一个MyStack< T>类,它实现任何接口你想要的(可能是List< T>?)

  • 在MyStack中为每个链表项创建一个私有静态最终类Node< T>内部类。每个节点都包含对类型为T的对象的引用和对下一个节点的引用。

  • 向MyStack添加topOfStack节点引用。

  • 推送和弹出操作只需要在这个topOfStack节点上运行。如果为null,则堆栈为空。我建议使用与标准Java堆栈相同的方法签名和语义,以避免以后混淆.....

  • 最后实现您需要的任何其他方法。对于奖励积分,实施Iterable< T>,以便在创建迭代器时记住堆栈的不可变状态,而无需任何额外的存储分配(此 可能:-) )

  • Create a "MyStack< T >" class which implements any interfaces you want (perhaps List < T >?)
  • Within MyStack create a "private static final class Node< T >" inner class for each linked list item. Each node contains a reference to an object of type T and a reference to a "next" Node.
  • Add a "topOfStack" Node reference to MyStack.
  • The push and pop operations just need to operate on this topOfStack Node. If it is null, the Stack is empty. I'd suggest using the same method signatures and semantics as the standard Java stack, to avoid later confusion.....
  • Finally implement any other methods you need. For bonus points, implement "Iterable< T >" in such a way that it remembers the immutable state of the stack at the moment the iterator is created without any extra storage allocations (this is possible :-) )