資料結構-用數組類比棧__資料結構

來源:互聯網
上載者:User

棧是一種抽象資料類型,是程式員的工具。

棧的特點:先入後出

push操作示意圖:

(圖是從浙大的資料結構慕課視頻上截得)


pop:


代碼:

/* * 使用數組實現棧 *  * 棧的特點:先入後出 *  * 2017年11月29日20:08:56 *  */public class ArrayStack{private int [] arr ;private int maxSize ;//指定數組長度private int Top ;//棧頂(索引)//初始化棧public ArrayStack ( int maxSize ){this.maxSize = maxSize ;arr = new int [maxSize];Top = -1 ;//代表當前棧中沒有元素}//入棧public void push ( int data ){//棧滿了就提示並直接返回if ( isFull () ){System.out.println ( "Sorry , 棧滿了" );return ;}arr [++Top] = data ;//入棧}//出棧public int pop (){// = -1 說明棧是空的if ( isEmpty () ){System.out.println ( "當前棧中沒有元素。" );return 0;}int temp = arr [Top--] ; //取出棧頂元素後索引-1return temp ;//返回棧頂元素}//判斷是否滿棧public boolean isFull (){return Top == maxSize - 1;//maxSize指的是數組長度,-1後表示實際索引範圍}//判斷棧是否為空白public boolean isEmpty (){return Top == -1 ;}//遍曆public void display (){if ( isEmpty () ){System.out.println ( "棧是空的" );return ;}//遍曆順序: 從頂到底System.out.println ( "Top -> bottom" );for ( int i = Top ; i >= 0 ; i -- ){System.out.print ( arr [i] + " " );}System.out.println ();}}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.