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) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(NULL==head||head->next==NULL)
return NULL;
ListNode* tmp1=head;
ListNode* tmp2=head;
for(int i=0;i<n;++i){
if(tmp1->next!=NULL)
tmp1=tmp1->next;
else{
head=head->next;
return head;
}
}
while(tmp1->next!=NULL){
tmp1=tmp1->next;
tmp2=tmp2->next;
}
if(tmp2->next->next){
ListNode* delNext=tmp2->next->next;
delete tmp2->next;
tmp2->next=delNext;
}
else{
delete tmp2->next;
tmp2->next=NULL;
}
return head;
}
};