栈(链表实现)

package com.dai.stack;
import java.util.Scanner;
public class LinkedListStack {
    public static void main(String[] args) {
        //先创建一个ArrayStack对象
        Stack stack = new Stack();
        String key = "";
        boolean loop = true;
        Scanner scanner = 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 = scanner.next();
            
            switch (key) {
            case "show":
                stack.list();
                break;
            case "push":
                System.out.println("请输入一个数:");
                int value = scanner.nextInt();
                Node newNode = new Node(value);
                stack.push(newNode);
                break;
            case "pop":
                try {
                    int res = stack.pop();
                    System.out.printf("出栈的数据是:%d
", res);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;
            case "exit":
                scanner.close();
                loop  = false;
                break;
            default:
                break;
            }
        }
        System.out.println("程序退出");
    }
}
class Stack{
    private Node top = null;
    //栈空
    public boolean isEmpty() {
        return top==null;
    }
    //入栈
    public void push(Node newNode) {
        if(isEmpty()) {
            top = newNode;
        }else {
        Node helper = top;
        top = newNode;
        top.next = helper;}
    }
    //出栈
    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;
        }
        Node helper = top;
        while(helper!=null) {
            System.out.println(helper);
            helper = helper.next;
        }
        System.out.println("遍历完成");
    }
    
}

class Node{
    public int value;
    public Node next = null;
    //构造器
    public Node(int value) {
        this.value = value;    
    }
    //为了显示方便,重写toString 方法
    @Override
    public String toString() {
        return "Node [value=" + value + "]";
    }
    
}
原文地址:https://www.cnblogs.com/shengtudai/p/14359656.html