Files
dsa-competitive-programming/leetcode/lc19/TwoPass.cpp
T
2026-02-11 14:56:22 +05:30

27 lines
631 B
C++

ListNode* removeNthFromEnd(ListNode* head, int n){
if(head == nullptr) return head;
ListNode* temp = head;
int count = 0;
while(temp!=nullptr) {
count++;
temp = temp->next;
}
if(n==count) {
ListNode* newHead = head->next;
delete head;
return newHead;
}
temp = head;
for(int i = 1; i<(count-n);i++){
temp = temp->next;
}
ListNode* nodeToDelete = temp->next;
temp->next = nodeToDelete->next;
delete nodeToDelete;
return head;
}
//n == count is when removal node is head
//count-n just goes to one node before the removal node