1, 原理
(1) 栈 (stack)本质上是一种动态集合,通过 后进先出(last-in, first-out LIFO) 的方式主要依靠 压入(PUSH)以及 弹出(POP)进行运作,例如:在叠罗汉时,不考虑特殊情况,五个人叠在一起,只有第五个人先起来了第四个人才能起来 同理 以此类推;再比如像家里装有弹簧的放盘子的容器,因为只有最上面的盘子才能被取下来的原因,所以盘子弹出的顺序是于压入的顺序相反的!
(2) 图例解释:
如图所示即为元素入栈和出栈的过程
如第一个栈所示栈S有4个元素,栈顶元素为6;第二个栈有四个元素,栈顶元素为9;第三个栈有6个元素,栈顶元素为7;三种栈的执行时间都为O(1).
2,代码
(1)main区域实现部分,此部分主要为实现Stack类中对应的方法(此部分无法实现循环清屏)
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Stack stack = new Stack(6);
boolean flag = true;
while(flag){
System.out.println("1, show | 2, exit | 3, push | 4, pop");
System.out.print("Your choice is: ");
int choose = input.nextInt();
switch (choose){
case 1:
stack.display();
break;
case 2:
System.exit(0);
break;
case 3:
System.out.print("Which value do you want to push: ");
int pushValue = input.nextInt();
stack.push(pushValue);
break;
case 4:
try {
int temp = stack.pop();
System.out.print("The pop value is: ");
System.out.print(temp);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
default:
break;
}
}
}
(2)Stack类 主要包含如下方法:
<1> 判断是否为空
public boolean isEmpty(){
return top == -1;
}
<2>判断是否满
public boolean isFull(){
return top == maxSize;
}
<3>PUSH
public void push(int value){
if(isFull()){
System.out.println("栈已满");
return;
}
top++;
stack[top] = value;
}
<4>POP
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈已空");
}
int value = stack[top];
top--;
return value;
}
<5>显示
public void display(){
if(isEmpty()){
System.out.println("栈空");
return;
}
for (int i = top; i >= 0 ; i--) {
System.out.print(stack[i] + " ");
}
System.out.println();
}
整体代码如下:
class Stack{
private int maxSize; //栈的大小
private int[] stack; //数组模拟栈
private int top = -1;
public Stack(int maxSize){
this.maxSize = maxSize;
stack = new int[this.maxSize];
}
public boolean isEmpty(){
return top == -1;
}
public boolean isFull(){
return top == maxSize;
}
public void push(int value){
if(isFull()){
System.out.println("栈已满");
return;
}
top++;
stack[top] = value;
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈已空");
}
int value = stack[top];
top--;
return value;
}
public void display(){
if(isEmpty()){
System.out.println("栈空");
return;
}
for (int i = top; i >= 0 ; i--) {
System.out.print(stack[i] + " ");
}
System.out.println();
}
}