欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java用链表实现栈的链式存储结构

程序员文章站 2022-03-25 18:45:33
...
package Stack;

public class StackLinkedList {

    int size = 0;

    Node head = null;

    public static void main(String[] args) {
        //测试
        StackLinkedList l = new StackLinkedList();
        l.push(1);
        l.push(2);
        l.push(2);
        l.push(2);
        l.push(2);
        l.pop();
        System.out.println(l.size);
    }

    public void push(int data){
        Node item = new Node(data);
        item.next = head;
        head = item;
        size++;
    }

    public int pop(){
        if (size == 0){
            throw new RuntimeException("stack is empty!");
        }
        else{
            Node destroy = head;
            head = head.next;
            int nodeData = destroy.data;
            destroy = null;
            size--;
            return nodeData;
        }
    }
}

class Node{
    int data;

    Node next = null;

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