- //转载raozhiyong11的
- package com.rao.util;
- import java.util.EmptyStackException;
- import java.util.Stack;
- public class MyStack<E> {
- private E[] eleDates; //数组对象
- private int topIndex; //最上一个元素(栈顶元素)的下标
- private int count; //元素的个数
- public MyStack(int size) {
- this.eleDates = (E[])new Object[size]; //初始化数组长度
- this.topIndex=-1; //初始化最后一个元素的下边
- this.count = 0; //初始化元素的个数
- }
- public MyStack() {
- this(10); //提供一个默认的构造函数,默认初始化数组的长度只能装10个元素
- }
- //压入
- public void push(E obj){
- if (isFull()) {
- throw new ArrayIndexOutOfBoundsException("栈已经满了,不能再放入元素");
- }else {
- count++; //栈中元素的个数+1
- this.eleDates[++topIndex]=obj; //在最后一个元素的后面增加当前元素
- }
- }
- //弹出栈,并且弹出栈顶元素
- public E pop(){
- if (isEmpty()) {
- throw new EmptyStackException();
- }else {
- count--; //栈中元素的个数-1
- E movedObj = this.eleDates[topIndex];
- this.eleDates[topIndex]=null; //设置被移除的对象为空
- topIndex--; //栈的元素下标-1
- return movedObj;
- }
- }
- //弹出栈顶元素
- public E peek(){
- if (isEmpty()) {
- throw new EmptyStackException();
- }else {
- return this.eleDates[topIndex];
- }
- }
- //判断栈是否为空
- public boolean isEmpty(){
- return this.topIndex==-1;
- }
- //判断栈是否已满
- public boolean isFull(){
- return this.topIndex==(this.eleDates.length-1);
- }
- //获取栈的长度
- public int getStackSize(){
- return this.eleDates.length;
- }
- // 获取栈中元素的个数
- public int getStackCount(){
- return this.count;
- }
- @Override
- public String toString() {
- String stackString = "";
- for (int i = 0; i < eleDates.length; i++) {
- if (eleDates[i]!=null) {
- stackString+=eleDates[i]+" | ";
- }
- }
- return stackString;
- }
- public static void main(String[] args) {
- MyStack<Integer> myStack = new MyStack<Integer>(5);
- myStack.push(2);
- myStack.push(100);
- myStack.push(5);
- myStack.push(12);
- myStack.push(33);
- System.out.println(myStack);
- System.out.println(myStack.pop());
- System.out.println(myStack);
- System.out.println(myStack.pop());
- System.out.println(myStack);
- System.out.println(myStack.pop());
- System.out.println(myStack);
- }
- }
运行结果:
- 2 | 100 | 5 | 12 | 33 |
- 33
- 2 | 100 | 5 | 12 |
- 12
- 2 | 100 | 5 |
- 5
- 2 | 100 |