Java用单链表实现一个简单队列和简单栈

小熊博客
2021-07-07 / 0 评论 / 275 阅读
温馨提示:
本文最后更新于2021-07-07,若内容或图片失效,请留言反馈。
public static void main(String[] args) {
        //测试先进先出
        MyQueue myQueue = new MyQueue();
        myQueue.add(10);
        myQueue.add(20);
        myQueue.add(30);
        myQueue.add(40);
        while (myQueue.peek() != null) {
            System.out.println(myQueue.get());
        }
        //测试先进后出
        MyStack myStack = new MyStack();
        myStack.add(10);
        myStack.add(20);
        myStack.add(30);
        myStack.add(40);
        while (myStack.peek() != null) {
            System.out.println(myStack.get());
        }
    }
    //节点
    public static class Node<V> {
        V value;
        Node<V> node;

        public Node(V value) {
            this.value = value;
            node = null;
        }
    }

    /**
     * 队列
     * @param <V>
     */
    public static class MyQueue<V> {
        Node<V> head;
        Node<V> tail;
        int size;

        public MyQueue() {
            head = null;
            tail = null;
            size = 0;
        }

        public int size() {
            return size;
        }

        public void add(V value) {
            Node<V> node = new Node(value);
            if (tail == null) {
                head = node;
                tail = node;
            } else {
                tail.node = node;
                tail = node;
            }
            size++;
        }

        public V get() {
            V info = null;
            if (head == null) {
                tail = null;
            } else {
                info = head.value;
                head = head.node;
                size--;
            }
            return info;
        }

        public V peek() {
            V info = null;
            if (head != null) {
                info = head.value;
            }
            return info;
        }
    }
    /**
     * 栈
     * @param <V>
     */
    public static class MyStack<V> {
        Node<V> head;
        int size;

        public MyStack() {
            head = null;
            size = 0;
        }

        public int size() {
            return size;
        }

        public void add(V value) {
            Node<V> node = new Node<V>(value);
            if (head == null) {
                head = node;
            } else {
                node.node = head;
                head = node;
            }
            size++;
        }

        public V get() {
            V info = null;
            if (head != null) {
                info = head.value;
                head = head.node;
                size--;
            }
            return info;
        }

        public V peek() {
            V info = null;
            if (head != null) {
                info = head.value;
            }
            return info;
        }
    }