circularly linked list 循环单链表

  • Without sentinel. Since it’s circularly, we only need a tail because head is tail.getNext().
public class CircularlyLinkedList<E> {
    private static class Node<E> {
        E element;
        Node<E> next;
        Node(E e, Node<E> nextNode) {
            element = e;
            next = nextNode;
        }
        Node<E> getNext() {
            return next;
        }
        E getElement() {
            return element;
        }
        void setNext(Node<E> nextNode) {
            next = nextNode;
        }
    }

    private int size;
    private Node<E> tail;

    public CircularlyLinkedList() {
        size = 0;
        tail = null;
    }
    public int size() {
        return size;
    }
    public boolean isEmpty() {
        return (size == 0);
    }
    public E first() {
        if (isEmpty()) return null;
        return tail.getNext().getElement();
    }
    public E last() {
        if (isEmpty()) return null;
        return tail.getElement();
    }
    public void rotate() {
        if (!isEmpty()) tail = tail.getNext();
    }
    public void addFirst(E e) {
        Node<E> temp = new Node<>(e, null);
        if (isEmpty()) {
            tail = temp;
            temp.setNext(temp);
        } else {
            temp.setNext(tail.getNext());
            tail.setNext(temp);
        }
        size++;
    }
    public void addLast(E e) {
        addFirst(e);
        rotate();
    }
    public E removeFirst() {
        if (isEmpty()) return null;
        Node<E> firstNode = tail.getNext();
        if (size == 1) tail = null;
        else tail.setNext(firstNode.getNext());
        size--;
        return firstNode.getElement();
    }
    public void printList() {
        if (isEmpty()) return;
        Node<E> temp = tail.getNext();
        for (int i = 0; i < size; i++) {
            System.out.print(temp.getElement() + " ");
            temp = temp.getNext();
        }
        System.out.println();
    }
}