Search code examples
javalisttraversaldoubly-linked-list

Java doubly linked list -- equality of two adjacent nodes


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.


Solution

  • You're right, the loop termination isn't exactly right. The first two branches within the while loop doesn't belong. One of the first two branches will always fire, as != and == are complements. The return false statement belongs outside of the while loop, indicating the entire list has been traversed and no equal adjacent nodes.

    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;
    }
    

    the use of hasNext() is perfect! never want to over-traverse a list... hope this helps!