首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java实现栈(链表形式)

2013-10-10 
java实现栈(链表方式)Node类public class NodeT {T dataNode T nextnullpublic Node(T data){this.

java实现栈(链表方式)

Node类

public class Node<T> {T data;Node <T> next=null;public Node(T data){this.data=data;}}


Stack类

public class Stack<T> {private Node<T> top;private int size;public void push(T data){Node<T> node1=new Node<T>(data);node1.next=top;this.top=node1;size++;}public Node<T> pop(){if (size==0)return null;else {Node<T> pre=this.top;this.top=this.top.next;size--;return pre;}}public int getSize(){return this.size;}public Node<T> getTop(){return this.top;}}


测试类

public class StackTest { public static void main(String[] args) { Stack<Integer> st=new Stack<Integer>(); st.push(1); st.push(2); st.push(3); st.push(4);  while(st.getTop()!=null)   {   System.out.println("size:"+st.getSize());   System.out.println("top:"+st.getTop().data);  System.out.println(st.pop().data); }  }}


 

热点排行