集册 Java实例教程 创建自己的堆栈

创建自己的堆栈

欢马劈雪     最近更新时间:2020-01-02 10:19:05

534
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
创建自己的堆栈
/* 来 自 时 代 J a v a 公 众 号 - N o w J a v  a . c o m*/



public class _02CustomLinkedList {

  public static void main(String[] args) {

    Stack stack = new Stack(3);

    stack.push(1);

    stack.push(2);

    stack.push(3);

    // stack.push(4);


    System.out.println(stack.pop());

    System.out.println(stack.pop());

    System.out.println(stack.pop());

    // System.out.println(stack.pop());
    /**来自 
     n o w j a v a . c o m**/

  }

}


class Stack {

  private int size;

  private int[] stackAr;

  private int top; // top of stack


  /**

   * Constructor for initializing Array.

   */

  public Stack(int size) {

    this.size = size;

    stackAr = new int[size]; // Creation of Stack array

    top = -1; // initialize Stack to with -1

  }


  /**

   * Push items in stack, it will put items on top of Stack.

   */

  public void push(int value) {

    if (isFull()) {

      throw new StackFullException("Cannot push " + value + ", Stack is full");

    }

    stackAr[++top] = value;

  }


  /**

   * Pop items in stack, it will remove items from top of Stack.

   */

  public int pop() {

    if (isEmpty()) {

      throw new StackEmptyException("Stack is empty");

    }

    return stackAr[top--]; // remove item and decrement top as well.

  }


  /**

   * @return true if Stack is empty

   */

  public boolean isEmpty() {

    return (top == -1);

  }


  /**

   * @return true if stack is full

   */


  public boolean isFull() {

    return (top == size - 1);

  }


}


class StackFullException extends RuntimeException {


  public StackFullException() {

展开阅读全文