首页 > 代码库 > java 实现链栈存储

java 实现链栈存储

package com.learn.algorithm.linkStack;
/**
 * 链栈实现
 * @author Jiekun.Cui
 * @param <T>
 */
public class LinkStack<T> {

    private LinkStack<T>.Node<T> top = new Node<T>();
    private int size=0;
    
    /**
     * 进栈
     * @param t
     * @return  ;
     */
    public boolean push(T t){
        
        if ( isEmpty() ) {
            top.next = new Node<T>(t);
            
        } else {
            Node<T> newNode = new Node<T>(t, top.next);
            top.next = newNode;
        }
        size ++ ;
        return true;
    }
    
    /**
     * 出栈
     * @param t
     * @return
     */
    public T pop(){
        
        if ( isEmpty() ) {
            return  null;
        } else {
            LinkStack<T>.Node<T> node = top.next;
            top.next = node.next;
            size --;
            return node.getT();
        }
    }
    
    
    /**
     * 获取栈顶元素
     * @return
     */
    public T getTop(){
        if ( isEmpty() ) {
            return  null;
        } else {
            return top.next.getT();
        }
    }
    
    
    /**
     * 判断栈是不是为空
     * @return
     */
    public boolean isEmpty(){
        return size() == 0;
    }
    
    /**
     * 返回栈的大小
     * @return
     */
    public int size(){
        return size;
    }
    
    
    
    
    /**
     * @author 链栈的节点类
     * @param <T>
     */
    class Node<T>{
        private T t = null;
        private Node<T> next = null;
        
        public Node(){
            
        }
        public Node(T t){
            this.t = t;
        }
        public Node(T t,Node<T> next){
            this.t = t;
            this.next =next;
        }
        
        
        public T getT() {
            return t;
        }
        public void setT(T t) {
            this.t = t;
        }
        
        public Node<T> getNext() {
            return next;
        }
        public void setNext(Node<T> next) {
            this.next = next;
        }
    }
}

 

package com.learn.algorithm.linkStack;

/**
 * 链栈测试
 * @author Jiekun.Cui
 */
public class Demo {
    
    public static void main(String[] args) {
        LinkStack<Integer> ls = new LinkStack<>();
        
        ls.push(1);
        ls.push(2);
        ls.pop();
        ls.push(4);
        ls.push(5);
        ls.push(6);
        
        
        while ( !ls.isEmpty() ) {
            System.out.println(ls.pop());
        }
        
    }

}

 以上代码。

java 实现链栈存储