数据结构之栈的java实现

package com.cb.java.algorithms.datastructure.yanweimindatastructure.list;


public class GenericStack<T> {


private int maxSize; // 栈的容量
private T[] stack; // 栈
private int top; // 栈顶元素


public GenericStack(int size) {
this.maxSize = size;
this.stack = (T[]) new Object[maxSize];
this.top = -1;
}


/**
* 入栈

* @param x
* @throws Exception
*/
public void push(T x) throws Exception {
if (isFull()) {
throw new Exception("栈已满,无法插入新的元素");
}
top++;
stack[top] = x;
}


/**
* 栈顶元素出栈

* @return
* @throws Exception
*/
public T pop() throws Exception {
if (isEmpty()) {
throw new Exception("栈已空,没有元素出栈");
}
return stack[top--];
}


public T peek() throws Exception {
if (isEmpty()) {
throw new Exception("栈已空,无法获取栈顶元素");
}
return stack[top];
}


/**
* 判断栈是否为空

* @return
*/
public boolean isEmpty() {
return this.top == -1;
}


/**
* 判断是否栈已满

* @return
*/
public boolean isFull() {
return this.maxSize - 1 == this.top;
}
}

猜你喜欢

转载自blog.csdn.net/u013230189/article/details/80654013