whats wrong in my code.
How to delete kth nodefrom end in LL
Hey I can’t see the output or anything in IDE , so can you please elaborate your issue.
actually iam solving an question on leetcode…where i have to dleted the nth node from LL and i have to complete the fucniton given there.
Please share the link to the same
your code is not handling the cases when we have to delete the head node.
So with the same code add a dummy node in the beggining of head and you can proceed with the same code otherwise you have to add many checks.
/**
-
Definition for singly-linked list.
-
struct ListNode {
-
int val; -
ListNode *next; -
ListNode() : val(0), next(nullptr) {} -
ListNode(int x) : val(x), next(nullptr) {} -
ListNode(int x, ListNode *next) : val(x), next(next) {} -
};
/
class Solution {
public:
ListNode removeNthFromEnd(ListNode* head, int n) {ListNode *temp =new ListNode(0); //added this temp ->next=head ; //did this ListNode *slow=temp; //updated this ListNode *fast=temp; //updated this int x=n+1; //updated this while(x--&&fast!=NULL) fast=fast->next; while(fast!=NULL) { fast=fast->next; slow=slow->next; } slow->next=slow->next->next; return temp->next; //updated this}
};
Mentioned changes in comments
sir why did you inc n by 1?
sir why did you inc n by 1? in a video it was told that inc the fast pointer by n and then insert while loop till the fast reaches the end of thr LINKED LISt the slow pointer will reach the Nth node. and print it.
But we have to delete it and not print it ,so we will be going to the node whose next node is the one which we have to delete,that’s why n+1
I dont think you are talking about the same question.
Please open another thread/doubt for the same and close this one .