Hello … i am doing this question on leetcode…
why this is showing error not able to understand
What is wrong here
change or to and
plus use a simple logic like this
mark a temp and a c both to head
run the loop for while c!=null
inside check while temp->next-> data is same as temp->data and a null check
temp->next = temp->next->next
basically skip nodes that have data as curr node
ListNode* deleteDuplicates(ListNode* head) {
if(head==NULL || head->next==NULL) return head;
ListNode* temp =head;
ListNode* c = head;
while(c)
{
temp = c;
while(temp->next && temp->val==temp->next->val)
{
temp->next = temp->next->next;
}
c = c->next;
}
return head;
}
my submission
For this code… https://ide.codingblocks.com/s/316527
If input is [1,1,2,3,3]
my output is coming [1]
Where the logic is failing
- Never modify head
- whenever u assign a node to c, c should also move
once c is at 1 and then u assign c’s next as 2, c is still c, next time u assign c’s next as 3, c is still at 1
then loop breaks u assign c’s next as null, so now what is the ll 1->NULL
this is ll with c, hence wrong
I have come up with a solution which got accepted…
But i am not able to understand your solution.
Could you explain a bit
Can you explain this code…
It is similar to your code… https://onlinegdb.com/SktOVDpzP
I am not able to understand what curr = curr->next is doing…
curr = curr->next means
that if curr is at 2 and it’s next is now at 3, we should make it 3
I’d suggest you do the following:
- dry run the code
- If you face difficulty in dry running the code, you should re watch the basic section of linked list, maybe from youtube, since this statement is very important to understand, if you miss this, you will face a lot of difficulty ahead, especially when more complex topics arrive
I understand that… Here i am not able to understand that… How this all ensure that when we return head… It will show the rigth output…
I have done this question myself… But there i have modefied the head…
And also used some extra space… Even after dry run i am not able to get that when we return head how it will show the rigth output
Hope you understand where i am confused… I am not getting how changing the curr pointer value will ensure that if we return head it will show the rigth output
because you are not modifying head, modifying some other pointer will keep the head intact
@ashishnnnnn
curr has been initialised to head at the beginning. Hence both curr and head point towards the same memory block. Any changes made to the memory block pointed by ‘curr’ will change the data in that memory block. Since it is the same pointed to by the head pointer as well , when we return head all those changes will be reflected as well.