希望大佬多多指正!!
package com.atguigu.stack;
import java.util.Scanner;
/**
* 单链表模拟栈
*/
public class SingleLinkedListStackDemo {
public static void main(String[] args) {
//测试一把
System.out.println("测试数组模拟栈的案例···");
//创建一个栈
SingleLinkedListStack stack = new SingleLinkedListStack();
String key = "";//接受用户输入
Scanner sc = new Scanner(System.in);
boolean loop = true;//循环判断
while (loop) {
System.out.println("show:显式栈");
System.out.println("exit:退出程序");
System.out.println("push:入栈");
System.out.println("pop:出栈");
System.out.println("请输入你的选择:");
key = sc.next();//接受一个字符串
switch (key){
case "show":
stack.list();
break;
case "push":
System.out.println("请输入一个数:");
stack.push(sc.nextInt());
break;
case "pop":
try {
System.out.printf("栈顶数据为%d\n", stack.pop());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case "exit":
sc.close();
loop=false;
break;
default:
break;
}
}
System.out.println("程序退出!");
}
}
//定义一个SingleLinkedListStack,表示栈
class SingleLinkedListStack{
//创建一个节点
Node head=new Node();
//判断节点是否为空
public boolean isEmpty(){
return head.getNext()==null;
}
//判断在链表尾部加入节点,入栈
public void push(int value){
Node newNode=new Node(value);
//得到最后一个节点
//定义一个辅助节点
Node temp=head;
boolean flag=false;//标志找到最后一个节点
while (true){
if (temp.getNext()==null){
//找到
flag=true;
break;
}
temp=temp.getNext();
}
if (flag){
//此时temp代表最后一个节点
temp.setNext(newNode);
}
}
//删除最后一个节点,出栈
public int pop(){
//判断链表是否为空
if (isEmpty()){
throw new RuntimeException("栈空");
}
//不为空
//定义一个辅助节点
Node temp=head;
boolean flag=false; //找到最后一个节点的前一个节点
int value=-1;//接收要删除节点的值
while (true){
if ((temp.getNext()!=null && temp.getNext().getNext()==null)){
flag=true;
break;
}
temp=temp.getNext();
}
if (flag){
//此时temp为倒数第二个节点
value = temp.getNext().getNo();
temp.setNext(null);
}
return value;
}
//显式栈的情况【遍历栈】,需要从栈顶开始显式数据
public void list(){
//判断链表是否为空
if (isEmpty()){
System.out.println("栈空!");
}
//不为空
//定义一个辅助节点
Node temp=head.getNext();
while (temp!=null){
System.out.println(temp);
temp=temp.getNext();
}
}
}
//定义一个节点
class Node{
private int no;//数据
private Node next;//指向下一个节点
//构造器
public Node() {
}
public Node(int no) {
this.no = no;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
@Override
public String toString() {
return "node{" +
"no=" + no +
'}';
}
}
希望大佬多多指正!!