顺序栈--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 }

 

posted @ 2017-10-17 10:53  sun1993  阅读(855)  评论(0编辑  收藏  举报