Repository containing solution for #SdeSheetChallenge by striver
Given the head of a linked list, remove the nth node from the end of the list and return its head.
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(n==0 || head == NULL) return head;
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;
}
};
slow->next = slow->next->next
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* fast = head,*slow = head;
if(n==0 || head == NULL) return 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;
}
};