单链表实现队列

public class Queue {
    // 单链表实现队列
    public static class Node<V> {
        public V value;
        public Node<V> next;

        public Node(V v) {
            value = v;
        }
    }

    public static class Queue<V> {
        private Node<V> head;
        private Node<V> tail;
        private int size;

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

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

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

        public V poll() {
            V ans = null;
            if (head != null) {
                ans = head.value;
                head = head.next;
                size--;
            } else {
                tail = null;
            }
            return ans;
        }

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


    public static void main(String[] args) {
        Queue<Integer> queue = new Queue<>();
        for (int i = 0; i < 10; i++) {
            queue.offer(i);
        }

        while (!queue.isEmpty()) {
            System.out.print(queue.poll() + " ");
        }
    }
}

你可能感兴趣的:(算法与数据结构,java,算法,c++)