Skip to content

Instantly share code, notes, and snippets.

@zhangxiaomu01
Created November 4, 2018 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangxiaomu01/1d58036c2d97a8e54cd1e4e09b9e8da7 to your computer and use it in GitHub Desktop.
Save zhangxiaomu01/1d58036c2d97a8e54cd1e4e09b9e8da7 to your computer and use it in GitHub Desktop.
/**
* 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