Ninja technique🥷 to ACE DSA Interviews.
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int len = 0;
ListNode *temp = head;
while (temp) {
len++;
temp = temp->next;
}
if (n == len) return head->next;
n = len - n;
temp = head;
while (--n) {
temp = temp->next;
}
ListNode* deleteNode=temp->next;
temp->next = temp->next->next;
delete deleteNode;
return head;
}
};
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* fast = head,*slow = head;
while(n--) fast = fast->next;
if(!fast) return head->next;
while(fast->next){
fast = fast->next;
slow = slow->next;
}
ListNode* deleteNode=slow->next;
slow->next = slow->next->next;
delete deleteNode;
return head;
}
};