Home  >  Article  >  Java  >  Java implements simple stack code

Java implements simple stack code

高洛峰
高洛峰Original
2017-01-24 14:42:271164browse

The example of this article shares the specific code for implementing a simple stack in Java for your reference. The specific content is as follows

/**
 * Created by Frank
 */
public class ToyStack {
  /**
   * 栈的最大深度
   **/
  protected int MAX_DEPTH = 10;
 
  /**
   * 栈的当前深度
   */
  protected int depth = 0;
 
  /**
   * 实际的栈
   */
  protected int[] stack = new int[MAX_DEPTH];
 
  /**
   * push,向栈中添加一个元素
   *
   * @param n 待添加的整数
   */
  protected void push(int n) {
    if (depth == MAX_DEPTH - 1) {
      throw new RuntimeException("栈已满,无法再添加元素。");
    }
    stack[depth++] = n;
  }
 
  /**
   * pop,返回栈顶元素并从栈中删除
   *
   * @return 栈顶元素
   */
  protected int pop() {
    if (depth == 0) {
      throw new RuntimeException("栈中元素已经被取完,无法再取。");
    }
 
    // --depth,dept先减去1再赋值给变量dept,这样整个栈的深度就减1了(相当于从栈中删除)。
    return stack[--depth];
  }
 
  /**
   * peek,返回栈顶元素但不从栈中删除
   *
   * @return
   */
  protected int peek() {
    if (depth == 0) {
      throw new RuntimeException("栈中元素已经被取完,无法再取。");
    }
    return stack[depth - 1];
  }
}

The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone Duoduo supports PHP Chinese website.

For more articles related to Java implementation of simple stack code, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn