Created
November 4, 2018 03:10
-
-
Save zhangxiaomu01/1d58036c2d97a8e54cd1e4e09b9e8da7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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