Java implementation simple Stack code _java

Source: Internet
Author: User

This example for you to share the Java implementation of a simple stack of the specific code for your reference, the specific contents are as follows

/**
 * Created by Frank */public
class Toystack {
  /**
   * Stack maximum depth
   **/
  protected int max_depth = Ten;

  /**
   * Current Depth of stack * *
  protected int depth = 0;

  /**
   * Actual stack *
  /protected int[] stack = new int[max_depth];

  /**
   * Push, add an element to the stack
   *
   * @param n to add the integer *
   *
  protected void push (int n) {
    if depth = = Max_d EPTH-1) {
      throw new RuntimeException ("The stack is full and no more elements can be added.") ");
    }
    stack[depth++] = n;
  }

  /**
   * Pop, return top element of stack and remove from stack
   *
   * @return stack top element
  /protected int pop () {
    if (depth = 0) {
      throw new RuntimeException ("The elements in the stack have been taken out and cannot be fetched.") ");
    }

    --depth,dept subtracts 1 and assigns a value to the variable dept, so that the depth of the stack is reduced by 1 (equivalent to removing from the stack). return
    stack[--depth];
  }

  /**
   * Peek, return top of stack element but not remove from stack
   *
   * @return
   /
  protected int peek () {
    if (depth = 0) {
      throw new RuntimeException ("The elements in the stack have been taken out and cannot be fetched.") ");
    }
    return stack[depth-1];
  }

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.