java实现泛型栈

来源:互联网 发布:mac os verilog 编辑:程序博客网 时间:2024/06/05 05:17
package com.test.common;public class LinkedStack<T> {private 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>();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;}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubLinkedStack<String> stack=new LinkedStack<String>();stack.push("jianghuiwen");stack.push("wangjun");System.out.println(stack.pop());}}

代码如上所示,创建了一个泛型的栈,并且提供pop和push两种操作方法。输出结果如图


0 0