A public method twoTogether() for the class MyList returns True, if and only if the list has two adjacent elements that are equal. You can assume that no list element (data) is null. Here are some examples: the list [a,b,c,d], would return false when calling this method. But a list [a,b,b,c] or [a,b,c,d,e,f,f]. The method returns true. Write the public method twoTogether. You can use the List interface references (fields: data, prev, next)(head,tail)(size) etc. Here is the code I have written:
public boolean twoTogether(){
currentNode = head;
while (currentNode.hasNext()){
if (currentNode.data != currentNode.next.data){
currentNode = currentNode.next;
}
else if (currentNode.data == currentNode.next.data){
return True;
}
}
return False;
}
Would this code correctly traverse a list testing for equality between two nodes? Am I implementing hasNext() correctly also? I was having a hard time figuring out how not to terminate the loop, or return true for the nested if, then false for the else statement.
hasNext()
. How are we supposed to know if it is correct? Also, what type isdata
? Unless it's a primitive, your equality checking is going to fail. (and I assume it is not, since you mentioned a chance it could benull
). – azurefroghasNext
method. If this is an assignment, you would do well to take note of the limitations, specificallyYou can use the List interface references (fields: data, prev, next)(head,tail)(size) etc
- I see nothing there about using methods to detect list end. – paxdiablo