java实现栈(链表方式)

来源:互联网 发布:网络传送带使用教程 编辑:程序博客网 时间:2024/05/17 13:13

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); }  }}


 

原创粉丝点击