栈的定义
把线性表的插入和删除运算限制在表的一端进行。通常将表中允许进行运算端成为栈顶,不允许运算的另一端成为栈底。由于栈顶位置是动态变化的,需要设置栈顶指示器。
栈常见的运算
进栈或入栈、出栈或退栈
栈的特性
后进先出
说明:和线性表一样,栈也有两种存储方式:线性栈和链表栈
用数组实现栈—Java代码实现
public class Stack {
int[] data; // 存数据的数组
private int size;
private int top;
public Stack(int size){
this.size = size;
data = new int[size];
top = -1;
}
public int getSize() {
return size;
}
public int getTop() {
return top;
}
/**
* 判断栈是否为空
* @return
*/
public boolean isEmpty(){
return top == -1;
}
/**
* 判断栈是否满了
* @return
*/
public boolean isFull(){
return top == size - 1;
}
/**
* 入栈
* @param i
* @return
*/
public boolean push(int i){
if(isFull())
return false;
top++;
data[top] = i;
return true;
}
/**
* 弹栈
* @return
* @throws Exception
*/
public int pop() throws Exception {
if(isEmpty())
throw new Exception("The Stack is Empty...");
return data[top--];
}
public int peek(){
return data[top];
}
public int getMin() throws Exception {
if(isEmpty())
throw new Exception("The Stack is Empty...");
int min = data[0];
for(int i = 1; i <= top; i++){
if(min > data[i]){
min = data[i];
}
}
return min;
}
public static void main(String[] args) throws Exception {
Stack stack = new Stack(5);
stack.push(2);
stack.push(1);
stack.push(3);
System.out.println("The peek is " + stack.peek());
System.out.println("The min is " + stack.getMin());
while(!stack.isEmpty()){
System.out.print(stack.pop());
}
}
}