I tried out the following code in java to remove duplicates from a linked list
public static LinkedListNode<Integer> removeDuplicates(LinkedListNode<Integer> head) {
LinkedListNode<Integer> ptr1=head;
LinkedListNode<Integer> ptr2=head.next;
if(head==null)
return null;
if(head.next==null)
return head;
while(ptr2!=null){
if(ptr1.data==ptr2.data){
ptr2=ptr2.next;
}else{
ptr1.next=ptr2;
ptr1=ptr2;
ptr2=ptr2.next;
}
}
ptr1.next=ptr2;
return head;
}
which takes the head of the linked list as input then after removing duplicates from it returns the head.
if we take the following sample input for a linked list
281 386 386 957 1022 1216 1232 1364 1428 1428 1428 1428 1501 1953
it's not removing duplicates as expected
I tried debugging it in vscode and was amazed to see that ptr1.data == ptr2.data
evaluates to false
when ptr1 is at 386 and ptr2 is at the 386 after the first 386 of the input
I also tried a getter for LinkedListNode even then
ptr1.getData()==ptr2.getData()
was coming out false
is there some concept related to memory allocation I'm not getting involving heaps or something?
if you're curious about the LinkedListNode
class
and the function used to create the linked list here they are:
public class LinkedListNode<T> {
T data;
LinkedListNode<T> next;
LinkedListNode (T data){
this.data=data;
}
T getData(){
return this.data;
}
}
and
static LinkedListNode<Integer> takeinput(){
Scanner sc = new Scanner(System.in);
int data = sc.nextInt();
LinkedListNode<Integer> head = new LinkedListNode<Integer>(data);
LinkedListNode<Integer> tail = head;
data=sc.nextInt();
while(data!=-1){
LinkedListNode<Integer> newNode = new LinkedListNode<Integer>(data);
if(head.next==null){
head.next=newNode;
tail=newNode;
}else{
tail.next=newNode;
tail= newNode;
}
data=sc.nextInt();
}
sc.close();
return head;
}
input:281 386 386 957 1022 1216 1232 1364 1428 1428 1428 1428 1501 1953 -1 it stops to take input after -1 is entered and returns the head of the generated linkedlist