singly linked list 单链表

  • With a head sentinel.
  • 重写equals()的同时还得重写hashCode()
public class SinglyLinkedList<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;
        }
        void setElement(E e) {
            element = e;
        }
    }
    private int size;
    private Node<E> headSentinel;
    private Node<E> tail;

    public SinglyLinkedList() {
        size = 0;
        headSentinel = new Node<>(null, null);
        tail = headSentinel;
    }
    public int size() {
        return size;
    }
    public boolean isEmpty() {
        return (size == 0);
    }
    public E first() {
        return (isEmpty()) ? null : headSentinel.getNext().getElement();
    }
    public E last() {
        return (isEmpty()) ? null : tail.getElement();
    }
    public void addFirst(E e) {
        Node<E> newHeadSentinel = new Node<>(null, headSentinel);
        headSentinel.setElement(e);
        headSentinel = newHeadSentinel;
        size++;
    }
    public void addLast(E e) {
        tail.setNext(new Node<>(e, null));
        tail = tail.getNext();
        size++;
    }
    public E removeFirst() {
        if(isEmpty()) return null;
        Node<E> firstNode = headSentinel.getNext();
        headSentinel.setNext(firstNode.getNext());
        size--;
        return firstNode.getElement();
    }
    public void printList() {
        Node<E> temp = headSentinel.getNext();
        for (int i = 0; i < size; i++) {
            System.out.print(temp.getElement() + " ");
            temp = temp.getNext();
        }
        System.out.println();
    }
    
    @Override
    public boolean equals(Object obj) {
        if (obj == null) return false;
        if (getClass() != obj.getClass()) return false;
        SinglyLinkedList other = (SinglyLinkedList) obj;
        if (size != other.size) return false;
        Node thisHead = headSentinel.getNext();
        Node otherHead = other.headSentinel.getNext();
        while (thisHead != null) {
            if (thisHead.getElement() != otherHead.getElement()) return false;
            thisHead = thisHead.getNext();
            otherHead = otherHead.getNext();
        }
        return true;
    }
    @Override
    public int hashCode() {
        return Objects.hash(size, headSentinel, tail);
    }
}