#Removing duplicated from a sorted linked list question

29 messages · Page 1 of 1 (latest)

drowsy cove
#

Hello regarding the following code I have the doubt, why am I returning the head? I understand the code, but my confusion comes from the fact that the head is never altered.
I feel as if I am given a linked list 1 -> 2 - > 2- > 2 and returning the same thing.

This code works

    Node removeDuplicates(Node head)
    {
        Node current = head;
        while(current.next!= null){
            if(current.next.data == current.data)
                current.next = current.next.next;
            else 
                current = current.next;
        }
        
        return head;```


again, my confusion comes from the head not being altered. It feels so odd.
trail etherBOT
#

Hey, @drowsy cove!
Please remember to /close this post once your question has been answered!

shadow steeple
#

head doesn't need to be altered, as the first element is never a duplicate.
but it (or any other element from the list) may now point to a different next element

#

so if we have 1 -> 2 -> 2 -> 3, head is the Node at 1
now we iterate over the loop

at some point we'll see, that the second 2 is a duplicate. So we mutate the second Node to point to the fourth Node (3) instead.

head will still be the first Node though

drowsy cove
#

Please bare me with me, sorry if I come off as rude, I am just trying to understand. How does the head get the information from the Node current = head to skip the following values?

shadow steeple
#

ahh i see

#

when you say Node current = head, you don't actually create a new Node

#

just a new reference that points to the same Node that head is already pointing at

rare bronze
#

nope

rare bronze
#

Set<E> doesnt have any duplicates

drowsy cove
#

in an ordered list thats an overkill and it only consumed extra space

shadow steeple
#

I think that was not the question though

drowsy cove
#

going back to what you where saying Cap, then that does not create a new node?

shadow steeple
#

yeah, let me get out ms paint :D

#

this is your list:

rare bronze
#

it referes to the head one

shadow steeple
#

now with current = head you get this:

rare bronze
#

if you dont create clone/new object instance

shadow steeple
#

current = current.next

#

current.next = current.next.next

#

and again current = current.next, till you reach the end

#

note that head now points to the list without duplicates (since we altered the list in place, not a copy of the list)

drowsy cove
#

ty so much i got it now!

#

i thought it made a new list

shadow steeple
#

you're welcome ^^