数据结构|模拟栈的实现(JAVA)

import java.util.Arrays; public class MyStack { //以数组实现 public int[] elem = new int[10]; public int usedSize; //构造器 public MyStack() { }//入栈 public void push(int val) { if (this.isFull()) { this.elem = Arrays.copyOf(this.elem, 2 * this.elem.length); }this.elem[this.usedSize] = val; ++this.usedSize; }//判断栈是否满 public boolean isFull() {return this.usedSize == this.elem.length; }//将栈顶元素出栈并返回 public int pop() { if (this.empty()) { throw new RuntimeException("栈为空!"); } else { --this.usedSize; return this.elem[this.usedSize]; } }//获取栈顶元素 public int peek() { if (this.empty()) { throw new RuntimeException("栈为空!"); } else { return this.elem[this.usedSize - 1]; } }//判断是否空 public boolean empty() { return this.usedSize == 0; }public int size() { return this.usedSize; } }


栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈
顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。
压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。
出栈:栈的删除操作叫做出栈。出数据在栈顶。
数据结构|模拟栈的实现(JAVA)
文章图片


【数据结构|模拟栈的实现(JAVA)】

    推荐阅读