欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java编程思想里的泛型实现一个堆栈类 分享

程序员文章站 2023-12-18 18:12:58
觉得作者写得太好了,不得不收藏一下。 对这个例子的理解: //类型参数不能用基本类型,t和u其实是同一类型。 //每次放新数据都成为新的top,把原来的top往下压一...

觉得作者写得太好了,不得不收藏一下。

对这个例子的理解:

//类型参数不能用基本类型,t和u其实是同一类型。

//每次放新数据都成为新的top,把原来的top往下压一级,通过指针建立链接。

//末端哨兵既是默认构造器创建出的符合end()返回true的节点。

复制代码 代码如下:

//: generics/linkedstack.java
// a stack implemented with an internal linked structure.
package generics;

public class linkedstack<t> {
  private static class node<u> {
    u item;
    node<u> next;
    node() { item = null; next = null; }
    node(u item, node<u> next) {
      this.item = item;
      this.next = next;
    }
    boolean end() { return item == null && next == null; }
  }
  private node<t> top = new node<t>(); // end sentinel
  public void push(t item) {
    top = new node<t>(item, top);
  }   
  public t pop() {
    t result = top.item;
    if(!top.end())
      top = top.next;
    return result;
  }
  public static void main(string[] args) {
    linkedstack<string> lss = new linkedstack<string>();
    for(string s : "phasers on stun!".split(" "))
      lss.push(s);
    string ss;
    while((ss = lss.pop()) != null)
      system.out.println(ss);
      //----- if put integer into the linkedlist
      linkedstack<integer> lii = new linkedstack<integer>();
      for(integer i = 0; i < 10; i++){
          lii.push(i);
      }
      integer end;
      while((end = lii.pop()) != null)
          system.out.println(end);
      //----- integer test end!
  }

 
}
/* output:
stun!
on
phasers
*/

上一篇:

下一篇: