0

I am doing a question of eliminating duplicates from LinkedList. have written this code in the if statement first I have written if(curr.data == curr.next.data) but it is showing wrong and in one test case it is showing runtime error. Isn't Both are same? What is the difference in using (curr.data.equals(curr.next.data))?

public static LinkedListNode<Integer> removeDuplicates(LinkedListNode<Integer> head) {
        //Your code goes here
        if (head == null)
            return null;
        LinkedListNode<Integer> curr = head;
        while(curr.next != null)
        {
            if(curr.data == curr.next.data)
            {
                curr.next = curr.next.next;
            }
            else
            {
                curr = curr.next;
            }
        }
        return head;
    }
Evg
  • 25,259
  • 5
  • 41
  • 83

1 Answers1

1

Change

while(curr.next != null)

to

while(curr != null)

In you if block you are checking curr.next = curr.next.next but what if curr.next.next is itself null, if it is null then your condition in while will cause an error.

Linux Geek
  • 957
  • 1
  • 11
  • 19
  • Will it cause an error if you set `curr.next` to `null`? I think it will just end the `while` loop as the condition is not met anymore. PS: It is `curr` not `cur`. – Wu Wei Oct 07 '21 at 08:27
  • 1
    @anarchist912 When `curr` itself is null then how would you access `curr.next` (as he/she had done in `while`). Consider there are only 2 nodes in the linked list and both of which has value 10. Now try running the loop, `if` condition is true so `curr` will be set to `curr.next.next` (which is `null`) so when it reaches `while` again condition `curr.next != null` will cause error as `curr` is already `null`. And yeah thank you I changed `cur` with `curr` now – Linux Geek Oct 07 '21 at 11:38