Add the method of the linked java list

advertisements

When adding a node to a linked list I guess the idea would be as follows:

Declare newNode
Add to the front if front == null
else if there is already a node in the list

However this does not seem to work

public boolean add (E e) {

  ListNode<E> newNode = new ListNode<E>(e,null);

  if (front == null){
      front = newNode;
      rear = newNode;
      objectCount++;
      return true;
  }

      front.next = newNode;
      rear.next = newNode;
      rear = newNode;
      objectCount++;
      return true;
}

but when I run this for the list "a","b","c","d","e" it doesn't return a list size of 5 but of size 2. What's going wrong here?


You're adding the new node next to your front and your rear nodes. In order to solve the problem, you should just add it to the rear node (assuming your list will only accept new values in the rear).

//front.next = newNode;
rear.next = newNode;
rear = newNode;
objectCount++;
return true;