Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int len = 0;
ListNode* h = head;
while(head){
len++;
head = head->next;
}
if(len == 1){
return h->next;
}
head = h;
int index = len - n;
if(index == 0) return head->next;
for(int i = 0; i< index - 1; i++){
head = head->next;
}
ListNode *temp = head->next;
head->next = head->next->next;
delete temp;
return h;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment