棧--java實現

來源:互聯網
上載者:User

標籤:log   clear   nod   private   tac   ack   builder   元素   creat   

棧:後進先出 LIFO
生活執行個體:先進電梯後出來

儲存元素的基本結構:

public class Node {    /*    元素有兩部分:    元素的值    下一個元素的引用     */    Object data;//資料域    Node next; //指標域    public Node(){}    public Node(Object data,Node next){        this.data=data;        this.next=next;    }}

實現棧:

/** * Created by yaming * 棧的鏈式儲存 */public class LinkStack{    private Node top;//棧頂元素    private int size;//當前棧大小    public LinkStack(){        top=null;    }    /**     * 當前棧的大小     * @return     */    public int length() {       return size;    }    /**     * 判斷棧是否為空白     * @return     */    public boolean isEmpty() {        return size==0?true:false;    }    /**     * 入棧     * @param data     * @return     */    public boolean push(Object data){        Node node=new Node(data,null);        if(isEmpty()){            top=node;        }else {            node.next=top;//把元素放在棧頂,引用指向棧頂            top=node;        }        size++;//元素入棧,棧頂上升        return true;    }    /**     * 出棧     * @return     */    public Object pop(){        if(isEmpty()){            return null;        }else {            Node value=top;//得到棧頂元素            top=top.next;//更新前端節點            value.next=null;//棧頂元素的引用設定為null,該元素被回收            size--;            return value.data; //出棧的元素        }    }    /**     * 返回棧頂元素     * @return     */    public Object peek(){        if(isEmpty()){            return null;        }        return top.data;    }    /**     * 遍曆棧     * @return     */    public String stack(){        if(isEmpty()){            return "[]";        }else {            StringBuilder stringBuilder=new StringBuilder("[");            for (Node current=top;current!=null;current=current.next){                stringBuilder.append(current.data.toString()+", ");            }            int length=stringBuilder.length();            return stringBuilder.delete(length-2,length).append("]").toString();        }    }  public void clear(){        top=null;        size=0;    }}

 

棧--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.