順序棧--Java實現

 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 }
相關文章
相關標籤/搜索