棧的Java簡單實現

來源:互聯網
上載者:User

標籤:search   cte   log   bsp   empty   code   ref   ack   table   

關於棧

  棧(Stack)是限定只能在一段進行插入和刪除操作的線性表。

  進行插入和刪除操作的一端稱為“棧頂”(top),另一端稱為“棧底”(bottom)。

  棧的插入操作稱為“入棧”(push),棧的刪除 操作稱為“出棧”(pop)。

  棧具有後進先出(LIFO),先進後出(FILO)的特性。

Java Stack 類 

  棧是Vector的一個子類,它實現了一個標準的後進先出的棧。

  堆棧只定義了預設建構函式,用來建立一個空棧。 堆棧除了包括由Vector定義的所有方法,也定義了自己的一些方法。

  除了由Vector定義的所有方法,自己也定義了一些方法:

序號 方法描述
1 boolean empty() 
測試堆棧是否為空白。
2 Object peek( )
查看堆棧頂部的對象,但不從堆棧中移除它。
3 Object pop( )
移除堆棧頂部的對象,並作為此函數的值返回該對象。
4 Object push(Object element)
把項壓入堆棧頂部。
5 int search(Object element)
返回對象在堆棧中的位置,以 1 為基數。
自定的Stack Class

  

package DataStructe;public class MyStack_Text {            static class mystack    {        int mytop;        int stack[];                public mystack(int num) {            mytop=-1;            stack=new int[num];        }        /*出棧*/        void mypop()        {            mytop--;        }        /*入棧*/        void mypush(int x)        {            mytop++;            stack[mytop]=x;                    }        /*判空*/        Boolean myisempty()        {            if(mytop==-1)                return true;            else                return false;        }        /*取棧頂元素*/        int mypeek()        {            int peek=stack[mytop];            return peek;        }        /*棧大小*/        int mysize()        {            return mytop+1;        }    }            public static void main(String[] args) {        mystack myStack=new mystack(20);        myStack.mypush(1);        myStack.mypush(2);        myStack.mypush(3);        myStack.mypush(4);        System.out.print("棧大小為"+myStack.mysize());        System.out.println();        for(int i=myStack.mytop;i>=0;i--)        {            int get=myStack.mypeek();            myStack.mypop();            System.out.println(get);        }            }        }

 

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