I have an add method for creating a linked list that is unordered and has a trailer node defined by
ListNode<E> front = new ListNode<E>(null,null);
from what I understand I can keep on adding values to the front of the list BUT since this is a Linked List implementation of a Set and I can’t have a duplicate values, I need to check the set (each listnode from front to trailer node) to make sure it does not have the new value I’m trying to add into the list. Here is my add method.
public boolean add(E e) {
ListNode<E> newNode = new ListNode<E>(e, null);
//point to trailer
newNode.next = front.next;
//front now points to newNode
front.next = newNode;
//front->newNode->trailer
objectCount++;
return true;
}
Now, to check the that the newNode is not already in the linked list I need to implement a contains method that checks each element in the list and returns true if it is in the linked list. IF it returns true then I don’t execute the add method above and if I don’t then I successfully add the value. So, I was thinking something along the lines of:
if(this.contains(newNode))
return false;
else {
newNode.next = front.next;
front.next = newNode;
}
But I don’t know how to implement my contains method successfully. Heres what I have:
public boolean contains(Object o) {
ListNode<E> o1 = (ListNode<E>) o;
if (o1.value == front.next.value)
return true;
else
return false;
}
I’m not sure how I can make the method contains, check each node for the Object o and return true if it is in the linked list and false otherwise. So, going forward, is my understanding correct on how I should implement this? And how can I fix my contains method?
Every node knows whats before and whats behind it. Thus:
Go over all previous nodes, until there is noone anymore, check them.
Go over all following nodes, until there is noone anymore, check them.
(Because it sounds like an exercise, without code. But you just have to “translate” the written words into code)
–tb