I am trying to check for duplicates in a private method I created. I don't think I am implementing it correctly. I was hoping to get some help. Below are the methods I need to check for duplicates and also the private Boolean method that checks for duplicates.
public LinkedList2<T> union( LinkedList2<T> other
)
{
LinkedList2 unionSet = new
LinkedList2() ;
LinkedList2 unionSet2 =
other;
Node curr;
for(curr = head; curr != null; curr
= curr.getNext())
{
unionSet.insertAtTail(curr.getData());
}
for(curr = unionSet2.head; curr !=
null; curr = curr.getNext())
{
if(!unionSet.contains(curr.getData())&&
checkingForDupes(unionSet)== false)
{
unionSet.insertInOrder(curr.getData());
}
}
return unionSet;
}
public LinkedList2<T> inter(
LinkedList2<T> other )
{
LinkedList2 interSet = new
LinkedList2<T> () ;
Node<T> interSet2 =
this.head;
Node<T> interSet3 =
other.head;
while(interSet2.getNext()!=null)
{
interSet3 =
other.head;
while(interSet3
!= null)
{
if(interSet2.getData().equals(interSet3.getData()) &&
checkingForDupes(interSet)== false)
{
interSet.insertInOrder(interSet3.getData());
}
interSet3 = interSet3.getNext();
}
interSet2 =
interSet2.getNext();
}
return interSet;
}
public LinkedList2<T> diff( LinkedList2<T>
other )
{
LinkedList2 diffList = new
LinkedList2 ();
Node<T> diff2 =
this.head;
Node<T> diff3 =
other.head;
while(diff2 != null)
{
diff3 =
other.head;
while(diff3 !=
null)
{
if(diff2.getData().equals(diff3.getData())
&& checkingForDupes(diffList)== false)
{
diff2 =
diff2.getNext();
}
diff3 = diff3.getNext();
}
diffList.insertInOrder(diff2.getData());
diff2 =
diff2.getNext();
}
return diffList;
}
private boolean checkingForDupes(LinkedList2<T>
other)
{
int currentIndex = 0;
for (Node<T> curr =
other.head; curr != null; curr = curr.getNext())
{
int nodeIndex =
0;
for
(Node<T>thing = other.head; thing!= null; thing =
thing.getNext())
{
if (currentIndex != nodeIndex &&
thing.equals(curr))
{
return true;
}
nodeIndex++;
}
currentIndex++;
}
return false;
}
In the given code the code to check for duplicates is little bit redundant as in both the loops starts from the other.head which is not required.The code is provided below:
private boolean checkingForDupes(LinkedList2<T>
other)
{
Node<T> curNode = other.head;
while (curNode)
{
Node<T> tempNode = curNode.getNext();
while (tempNode)
{
if (tempNode.equals(curNode))
{
return true;
}
tempNode = tempNode.getNext();
}
curNode = curNode.getNext();
}
return false;
}
Get Answers For Free
Most questions answered within 1 hours.