/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int i=0;
ListNode* pos=head;
while(pos&&i<n-1) {
pos=pos->next;
i++;
}
if (pos==NULL) {
return head;
}
ListNode* pre=head;
ListNode* ppre=NULL;
while(pos->next) {
ppre=pre;
pre=pre->next;
pos=pos->next;
}
if (ppre==NULL) {
return head->next;
}
ppre->next=pre->next;
pre->next=NULL;
delete pre;
return head;
}
};
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int i=0;
ListNode* pos=head;
while(pos&&i<n-1) {
pos=pos->next;
i++;
}
if (pos==NULL) {
return head;
}
ListNode* pre=head;
ListNode* ppre=NULL;
while(pos->next) {
ppre=pre;
pre=pre->next;
pos=pos->next;
}
if (ppre==NULL) {
return head->next;
}
ppre->next=pre->next;
pre->next=NULL;
delete pre;
return head;
}
};