JAVA順序棧操作——初始化、入棧、出棧、判斷空棧、判斷棧滿__JAVA

來源:互聯網
上載者:User

順序棧:使用一組連續的記憶體依次儲存棧中的資料,定義一個top變數來儲存棧頂序號。

棧結構是“後進先出”的原則。

棧的最基本操作有兩個:push(入棧) + pop(出棧)


import java.util.Scanner;/** *  @author   LilyLee * @date     2017年4月25日 * @time     下午4:25:15 * @Version  1.0 * @email    lilylee_1213@foxmail.com * */public class Mystack {public static void main(String[] args) {Stack_type st=new Stack_type();Stack_Data data1=new Stack_Data();Stack_type stack =st.STinit(); //初始化棧Scanner sc=new Scanner(System.in);System.out.println("input  name age end with name='0'"); //輸入棧元素,以0結束while(true){Stack_Data sdata=new Stack_Data();sdata.name=sc.next();if(sdata.name.equals("0")){break;}sdata.age=sc.nextInt();st.PushST(stack, sdata);}String flag="1";System.out.println("pop stack  end with 0");//輸入任意非0元素完成彈棧flag=sc.next();while(!(flag.equals("0"))){data1=st.PopST(stack);if(data1==null){break;}System.out.println(data1.name+" "+data1.age);flag=sc.next();}System.out.println("End and Free");st.STFree(st);}}class Stack_Data{String name;int age;}class Stack_type{static final int MAXLEN=50; //定義棧的最大長度Stack_Data[] data=new Stack_Data[MAXLEN+1];int top;Stack_type STinit(){Stack_type p;if((p=new Stack_type())!=null){  //申請棧記憶體p.top=0;return p;}return null;}boolean STIsEmpty(Stack_type s){  //判斷棧是否為空白boolean t;t=(s.top==0);return t;}boolean STIsFull(Stack_type s){  //判斷棧是否已滿boolean t;t=(s.top==MAXLEN);return t;}void STClear(Stack_type s){  //清空棧s.top=0;}void STFree(Stack_type s){ //釋放棧所佔用空間if(s!=null){s=null;}}int PushST(Stack_type s,Stack_Data data){if((s.top+1)>MAXLEN){return 0;}  //棧溢出s.data[++s.top]=data;return 1;}Stack_Data PopST(Stack_type s){if(s.top==0){System.out.println("no elements!"); return null;} //棧為空白,操作失敗return (s.data[s.top--]);}Stack_Data PeekST(Stack_type s){if(s.top==0){System.exit(0);}  //棧為空白,操作失敗return (s.data[s.top]);}}


聯繫我們

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