堆栈就是先进后出的容器,好比一个杯子一样,下面用java来实现出来:

(其实用数组也可以模拟栈的实现,一个初始大小的数组,push和pop操作完全可以按照你的逻辑控制来进行压栈和弹栈,用一个int类型的变量做栈顶的索引值就好了,数组中所谓的弹栈其实就是索引值减小一个,然后不管被弹出的那个数组元素了)

数组来模仿实现,有个弊端就是初始有个大小限制,并不能动态增大或减小容量,所以我们来看一下链表的堆栈实现:

public class StackByLink {
    public Node front; //栈顶指针
    public Node rear;  //栈底指针

    class Node {
        int data;
        Node next;

        public Node(int data) {
            this.data = data;
            this.next = null;
        }
    }


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

    public void print() {
        Node current = front;
        while (current!=null) {
            System.out.println("current data: " + current.data);
            current = current.next;
        }
    }

    public void push(int data) {
        Node node = new Node(data);
        if(isEmpty()) {
            front = node;
            rear = node;
        } else {
            node.next = front;
            front = node;
        }
    }

    public void pop() {
        Node node;
        if(isEmpty()) {
            System.out.println("===目前空栈===");
            return;
        }
        node = front;
        //当栈中只有一个元素时
        if(node == rear) {
            front = null;
            rear = null;
            System.out.println("===操作之后,目前空栈===");
        } else {
            front = front.next;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
        StackByLink sbl = new StackByLink();
        int choice = 0;
        while (true) {
            System.out.println("(0)结束 (1)在堆栈push数据 (2)弹出数据");
            choice = Integer.parseInt(buf.readLine());

            if(choice == 2) {
                sbl.pop();
                System.out.println("弹栈之后堆栈内容为:");
                sbl.print();
            } else if(choice == 1) {
                System.out.println("请输入要加入堆栈的数据:");
                choice = Integer.parseInt(buf.readLine());
                sbl.push(choice);
                System.out.println("插入之后堆栈内容为:");
                sbl.print();
            } else if(choice == 0) {
                break;
            } else {
                System.out.println("输入错误!!");
            }
        }
    }

}

运行结果:
运行截图

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐