全站最帅😎
发布于 2020-05-14 / 1472 阅读
0
0

数据结构:栈(单链表实现)

上一篇博客:数据结构:栈(数组实现) 中通过数组实现了栈,这次我们通过单链表来实现,基本思路如图所示:
image.png
Java代码如下:

/**
 * @author lichen
 * @version 1.0.0
 * @date 2020-05-14 15:40
 */
public class MyStack {

    Node node;
    private int size;

    public boolean isEmpty() {
        return size == 0;
    }

    public Object peek() {
        if (isEmpty()) {
            return null;
        }
        return node.data;
    }

    public Object push(Object data) {
        Node top = node;
        node = new Node(data, top);
        size++;
        return data;
    }

    public Object pop() {
        if (isEmpty()) {
            return null;
        }
        Node top = node;
        // GC
        node = null;
        node = top.next;
        size--;
        return top.data;
    }

    public int size() {
        return size;
    }

    static class Node {
        Object data;
        Node next;
        public Node(Object data, Node next) {
            this.data = data;
            this.next = next;
        }
    }


    public static void main(String[] args) {
        MyStack stack = new MyStack();
        stack.push(4);
        stack.push(5);
        stack.push(6);
        stack.push(7);
        stack.push(8);
        stack.pop();
        stack.pop();
        System.out.println("size: " + stack.size());
        System.out.println(stack.peek());
        stack.pop();
        System.out.println(stack.isEmpty());
        stack.pop();
        stack.pop();
        System.out.println("size: " + stack.size());
        stack.pop();
        stack.push(9);
    }

}


评论