栈的特性:先进后出
栈就相当于往井里扔石头,一块一块往下扔,取的时候必须是从最上面拿出来,就是最后扔下去的;
如果数据保存的顺序和使用数据相反,可以考虑将数据存放到栈中。
栈有两个常规操作:入栈 和 出栈
利用数组实现栈:
public class Statck {
private int[] data = new int[6];
private int index = 0;
/**
* 入栈操作
* @param d
* @return
*/
public boolean push(int d) {
if (index < data.length) {
data[index] = d;
index ++;
return true;
}
System.out.println("栈已满");
return false;
}
/**
* 出栈操作
* @return
*/
public int pop() {
int t = -Integer.MAX_VALUE;
if (index > 0) {
index --;
t = data[index];
}else {
System.out.println("栈已空");
}
return t;
}
/**
* 打印操作
*/
public void print() {
for (int i = 0; i < index; i ++) {
System.out.print(data[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
Statck stack = new Statck();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.push(6);
stack.print();
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
stack.print();
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
结果: