用单链表实现栈的出栈和压栈

package stack.linkedListStack;
import java.util.Scanner;

public class LinkedListStackDemo {
    public static void main(String[] args) {

        //测试链表栈
        SingleLinkedList StackList=new SingleLinkedList();
        String key="";
        boolean loop=true;
        Scanner input=new Scanner(System.in);
        while(loop){
            System.out.println("show:表示显示栈");
            System.out.println("exit:表示退出栈");
            System.out.println("push:表示添加数据(入栈)");
            System.out.println("pop:表示删除数据(出栈)");
            System.out.println("请输入你的选择");
            key=input.next();
            switch (key){
                case "show":
                    StackList.list();
                    break;
                case "push":
                    System.out.println("请输入要添加的数据");
                    int v=input.nextInt();
                    StackList.push(v);
                    break;
                case "pop":
                    try {
                        int res=StackList.pop();
                        System.out.printf("出栈的数据是%d\n",res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case "exit":
                    input.close();
                    loop=false;
                    break;
                default:
                    break;
            }
        }
    }
}

//创建链表
class SingleLinkedList{
    public StackNode top;

    //添加链表
    public void push(int data){
        StackNode node=new StackNode(data);
        if(top==null){
            top=node;
        }else{
            node.next=top;
            top=node;
        }
    }

    //删除链表
    public int pop(){
        if (isEmpty()){
            throw new RuntimeException("栈是空的");
        }
        int value=top.value;
        top=top.next;
        return value;
    }

    //显示链表
    public void list(){
        if (isEmpty()){
            System.out.println("链表为空");
            return;
        }
        StackNode temp=top;
        while(true){
            System.out.printf("链表:%d\n",temp.value);
            if (temp.next==null){
                break;
            }
            temp=temp.next;
        }
    }

    public boolean isEmpty() {
        return top == null;
    }

}
class StackNode{
    public int value;
    public StackNode next;

    public StackNode(int value){
        this.value=value;
    }

    @Override
    public String toString() {
        return "StackNode{" +
                "value=" + value +
                ", next=" + next +
                '}';
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值