• 顺序栈--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 }
  • 相关阅读:
    0841. Keys and Rooms (M)
    0478. Generate Random Point in a Circle (M)
    0714. Best Time to Buy and Sell Stock with Transaction Fee (M)
    0535. Encode and Decode TinyURL (M)
    1721. Swapping Nodes in a Linked List (M)
    0823. Binary Trees With Factors (M)
    1461. Check If a String Contains All Binary Codes of Size K (M)
    0623. Add One Row to Tree (M)
    1332. Remove Palindromic Subsequences (E)
    0706. Design HashMap (E)
  • 原文地址:https://www.cnblogs.com/sun1993/p/7680494.html
Copyright © 2020-2023  润新知