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;
You shouldn't modify the next pointer inside the front node. If a front node exists, follow this steps:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.