Search code examples
javanodesdoubly-linked-list

How to do a cyclic doubly link list add method in java


I am implementing the add(E) method in the cyclic DoublyLinkedList class as well as the Node inner class.

Node should be implemented as a private inner class.

DoublyLinkedList's "first" attribute should point to the first node in the list. Its "size" attribute should store the number of elements in the list.

I am struggling on my add method, because it feels like nothing is wrong and I don't know what else I can add this this code that can fix it.

Therefore a brief introduction on what the add method should do.

The add(E) method should add the value parameter to the end of the list. Be sure to address the case in which the list is empty and/or the added element is the first in the list.

Here's my code:

public class DoublyLinkedList<E>
{
private Node first;
private int size;

@SuppressWarnings("unchecked")
public void add(E value)
{
    if(first == null)
    {
        first = new Node(value, null, null);
        first.next = first;
        first.prev = first;
    }
    else
    {
        first = new Node(value, first.next, first.prev);
        first.next = first.prev;
        first = first.next;
        first.prev = first;
    }
    size++;
}
private class Node<E>
{
    private E data;
    private Node next;
    private Node prev;

    public Node(E data, Node next, Node prev)
    {
        this.data = data;
        this.next = next;
        this.prev = prev;
    }
  }
 }

Solution

  • Code fixed with minimal change (just the else case in add):

    class DoublyLinkedList<E>
    {
        private Node first;
        private int size;
    
        public void add(E value)
        {
            if(first == null)
            {
                first = new Node(value, null, null);
                first.next = first;
                first.prev = first;
            }
            else
            {
                first.prev.next = new Node(value, first, first.prev);
                first.prev = first.prev.next;
            }
            size++;
        }
    
        private class Node<E>
        {
            private E data;
            private Node next;
            private Node prev;
    
            public Node(E data, Node next, Node prev)
            {
                this.data = data;
                this.next = next;
                this.prev = prev;
            }
        }
    }