HelenWang
HelenWang

Reputation: 203

Remove Duplicates from Sorted List

For example:

My question is why the returned object is head but not node? And Why node.next means the node traversal moves to next node ? I am confused:

public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null)
            return null;
        ListNode node = head;
        while(node.next != null) {
            if(node.val == node.next.val) {
                node.next = node.next.next;
            } else {
                node = node.next;

            }
        }
        return head;
    }
}

Upvotes: 2

Views: 359

Answers (2)

Andreas
Andreas

Reputation: 159165

To help understand, I'll suffix the values with letters to see the different instances, e.g. if original list is 1→1→1→2→2→3→3, that would then be 1a→1b→1c→2a→2b→3a→3b

The goal is to remove duplicates, and it progresses as follows:

Start at head: node = head

↓
1a→1b→1c→2a→2b→3a→3b

Remove 1b: node.next = node.next.next

↓
1a→1c→2a→2b→3a→3b

Remove 1c: node.next = node.next.next

↓
1a→2a→2b→3a→3b

Move forward: node = node.next

   ↓
1a→2a→2b→3a→3b

Remove 2b: node.next = node.next.next

   ↓
1a→2a→3a→3b

Move forward: node = node.next

      ↓
1a→2a→3a→3b

Remove 3b: node.next = node.next.next

      ↓
1a→2a→3a

Exit loop: node.next != null
Return updated list: head

↓
1a→2a→3a

As you can see, node.next = node.next.next doesn't actually move you forward, but to does progress you a step further to your goal.

You have to return head, otherwise you'd just return the last node, i.e.

↓
3a

and you don't want that.

Upvotes: 2

Scott Hunter
Scott Hunter

Reputation: 49893

The function returns a list; lists are represented by the head node. As for the bit about node.next: because that is what it is designed to do.

Upvotes: 0

Related Questions