Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
-
/**
-
* Definition for singly-linked list.
-
* struct ListNode {
-
* int val;
-
* ListNode *next;
-
* ListNode(int x) : val(x), next(NULL) {}
-
* };
-
*/
-
#include <iostream>
-
using namespace std;
-
-
class Solution {
-
public:
-
ListNode* removeNthFromEnd(ListNode* head, int n) {
-
ListNode* end_p,* p,*pre_p;
-
-
end_p=p=pre_p=head;
-
-
-
if(p==NULL) return head;
-
else if(p->next == NULL )
-
{
-
delete(p);
-
head=NULL;
-
return head;
-
}
-
-
n--;
-
while(n)
-
{
-
end_p = end_p->next;
-
n--;
-
}
-
-
-
while(end_p->next!=NULL)
-
{
-
pre_p=p;
-
end_p=end_p->next;
-
p=p->next;
-
}
-
-
-
if(pre_p==p) head = p->next;
-
else pre_p->next=p->next;
-
delete(p);
-
-
-
return head;
-
}
-
};
阅读(966) | 评论(0) | 转发(0) |