码迷,mamicode.com
首页 > 编程语言 > 详细

java 实现链栈存储

时间:2017-08-13 20:49:13      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:出栈   out   sem   --   span   []   str   获取   pack   

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 实现链栈存储

标签:出栈   out   sem   --   span   []   str   获取   pack   

原文地址:http://www.cnblogs.com/Jiekun-Cui/p/7354533.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!