java 實現鏈棧儲存

來源:互聯網
上載者:User

標籤:出棧   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 實現鏈棧儲存

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.