0
How can I check if 2 values in a linked list are the same using java?
2 Respostas
+ 2
You can sort the list and then check all naighbor elements if they are the same.
Or compare every element with every other element in the list if they are the same.
0
// this solution traverses list and get node1 and node2, then compare their values.
//for demonstrate, you can replace end of your code (from main() to end of code) with this, and run:
public static void main(String[] args) {
var list = new Holder2();
list.insert(list, 1);
list.insert(list, 2);
list.insert(list, 3);
list.insert(list, 2);
printList(list);
System.out.println();
System.out.println(list.getNode(1).data == list.getNode(3).data );
}
} //end of Holder
class Holder2 extends Holder {
public Node getNode(int index) {
int count = 0;
Node currNode = head;
while (count++ < index) {
if (currNode.next != null)
currNode = currNode.next;
else
throw new IndexOutOfBoundsException(
"\nrequired index: "+index+", max index: "+ (--count));
}
return currNode;
} }
/*output:
LinkedList: 1 2 3 2
true
*/