標籤:style i++ ott splay 實現 public 出棧 順序 受限
1 /*棧和隊列:邏輯結構屬於操作受限的線性表 2 *棧:特點先進後出,只允許在棧頂操作 3 *棧的實現方式:順序棧和鏈棧 4 *常見的操作:進棧,出棧,擷取棧頂,判空,判滿,棧的容量 5 *棧的應用 6 *1.逆序相關操作 7 *2.分隔字元匹配 8 * */ 9 //順序棧10 public class MyStack {11 private long[] arr;12 private int maxSize;//棧的容量13 private int top;//棧頂指標14 15 public MyStack(int s) {16 maxSize = s;17 arr = new long[maxSize];18 top = -1;19 }20 21 public boolean isFull(){22 return top == maxSize - 1;23 }24 25 public boolean isEmpty(){26 return top == -1;27 }28 29 //進棧必須先判斷滿了嗎30 public void push(long key){31 if(!isFull()){32 arr[++top] = key;33 }34 }35 36 //出棧前判斷是否為空白37 public long pop(){38 long num = 0;39 if(!isEmpty()){40 num = arr[top--];41 }42 return num; 43 }44 45 //得到棧頂元素46 public long getPeek(){47 return arr[top];48 }49 50 //顯示棧的元素51 public void diaplayStack(){52 for(int i = top;i >= 0; i--){53 System.out.print(arr[i] + " ");54 }55 System.out.println();56 }57 58 public int size(){59 return top + 1;60 }61 62 public long getPeekN(int n){63 return arr[n];64 }65 66 public void displayStack(String s){67 System.out.println(s);68 System.out.println("stack----bottom to top");69 for(int i = 0; i < size(); i++){70 System.out.print(getPeekN(i) + " ");71 }72 System.out.println();73 }74 75 }
順序棧--Java實現