I was asked to write a method that runs on a Linked List and checks if 2 of the lists contain the same values (It doesn't have to be the same order of values between them both).
Here's my code:
public boolean Equals(Object obj) {
if(obj instanceof LinkedList) //Checks if the object it got is a Linked List
{
if(this.length() != ((LinkedList)obj).length())
return false;
Node head1 = head;
Node head2 = ((LinkedList) obj).getHead();
boolean ans = false;
this.toString();
((LinkedList)obj).toString();
while(head1 != null)// Running on the 1st list values
{
while(head2 != null) { // comparing each value in the 2nd list to see if it's on the 1st list as well
if(head2.getValue() == head1.getValue())
ans = true;
head2 = head2.getNext();
}
if(ans == false)
return false;
ans = false;
head1 = head1.getNext();
}
return true;
}
else
return false;
}
I'm adding also the structure's class that you wouldn't have any difficulties on understanding:
public class LinkedList {
// Attributes
private Node head, tail;
private int length;
// Constructor
public LinkedList() {
head = tail = null;
length = 0;
}
// getHead
public Node getHead() {
return head;
}
// getTail
public Node getTail() {
return tail;
}
// Length
public int length() {
return length;
}
// isEmpty
public boolean isEmpty() {
return head == null;
}
It returns false on all the cases no matter what, I don't manage to enter my error, thanks a lot!!