/**
* 动态栈演示代码
*/
package com.szy.structure.stack;
import java.util.Scanner;
public class DynamicStack {
private Node TOP;
DynamicStack(){
TOP=null;
}
/**
* 判断栈是否为空
* @return
*/
public boolean isEmpty(){
if(null==TOP){
return true;
}
return false;
}
/**
* 压栈
* @param info
*/
public void push(int info) {
Node newNode=new Node();
newNode.info=info;
newNode.next=TOP;
TOP=newNode;
System.out.println(info+" 被压入栈中");
}
/**
* 出栈
*/
public void pop() {
System.out.println(TOP.info+" 出栈成功");
TOP=TOP.next;
}
/**
* 输出栈中信息
*/
public void display() {
if (isEmpty()) {
System.out.println("空栈");
}
else {
System.out.println("栈中信息:");
for (Node temp=TOP;temp!=null;temp=temp.next) {
System.out.println(temp.info+" ");
}
System.out.println("\n");
}
}
public static void main(String[] args) throws Exception{
DynamicStack stack=new DynamicStack();
int choice=0;
while(true)
{
System.out.println("---MENU---");
System.out.println("1.Push");
System.out.println("2.Pop");
System.out.println("3.Display");
System.out.println("4.Exit");
System.out.println("----------");
System.out.println("请选择:");
Scanner scanner=new Scanner(System.in);
choice=scanner.nextInt();
switch (choice) {
case 1:
{
System.out.println("请输入数字:");
int input=scanner.nextInt();
stack.push(input);
}
break;
case 2:
{
if (stack.isEmpty()) {
System.out.println("空栈!");
break;
}
stack.pop();
}
break;
case 3:
{
stack.display();
}
break;
case 4:
return;
default:
System.err.println("无效的输入!");
break;
}
}
}
}
//声明节点
class Node{
public int info;
public Node next;
}