链表来模拟栈
public class LinkedStackDemo {
public static void main(String[] args) {
StackNodeList stackNodeList=new StackNodeList();
int key=-1;
boolean loop=true;//控制是否退出菜单
Scanner scanner=new Scanner(System.in);
while (loop){
System.out.println("1:表示显示栈");
System.out.println("2:退出程序");
System.out.println("3:入栈");
System.out.println("4:出栈");
System.out.println("请输入你的选择");
key=scanner.nextInt();
switch (key){
case 1:
stackNodeList.list();
break;
case 2:
scanner.close();
loop=false;
break;
case 3:
System.out.println("请输入你的要入栈的值");
int next = scanner.nextInt();
stackNodeList.push(next);
break;
case 4:
try {
int pop = stackNodeList.pop();
System.out.printf("出栈的数据是%d \n",pop);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
default:
break;
}
}
}
}
class StackNodeList{
public StackNode head=new StackNode(0);
public StackNode top=head;
public boolean isEmpty(){
return top==head;
}
public void push(int value){
StackNode stackNode = new StackNode(value);
top.next=stackNode;
top=top.next;
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈空无法取出数据");
}
StackNode temp=head;
while (true){
if(temp.next==top){
break;
}
temp=temp.next;
}
int val=top.value;
top=temp;
top.next=null;
return val;
}
public void list(){
if (isEmpty()){
System.out.println("栈空,无数据");
return;
}
StackNode temp2=head.next;
while (temp2!=null){
System.out.println(temp2.value);
temp2=temp2.next;
}
}
}
class StackNode{
public int value;
public StackNode next;
public StackNode(int value) {
this.value = value;
}
@Override
public String toString() {
return "StackNode{" +
"value=" + value +
'}';
}
}