栈:先进后出
(在微博看到一个很形象的比喻:吃多了吐是栈,吃多了拉是队列~)
1.入栈
2.出栈
3.得到栈顶元素
class MyStack{
private int[] elem;//实现栈的大小
private int top; //当前可以存放数据的下标
public MyStack() {
this(10);
}
public MyStack(int size) {
this.elem = new int[size];
this.top = 0;
}
public void push(int val) { //压栈
if(isFull()) {
return;
}
this.elem[this.top++] = val;
}
public boolean isFull() { //判断栈是否已满
if (this.top == this.elem.length) {
return true;
}return false;
}
public boolean isEmpty() { //判断是否为空
if(this.top == 0) {
return true;
}return false;
}
public void pop() { //出栈
if(isEmpty()){
return;
}
this.top --;
}
public int getTop() { //得到栈顶元素
return this.elem[this.top-1];
}
}
public class TestStackDemo {
public static void main(String[] args) {
MyStack myStack = new MyStack();
myStack.push(10);
myStack.push(20);
myStack.push(30);
/* for (int i = 0; i < 20; i++) {
myStack.push(i);
}//0 1 2 3 4 5 6 7 8 9*/
myStack.pop();//9
System.out.println(myStack.getTop());//8
}
}