題目描述:
給定一個鏈表,刪除鏈表的倒數第 n 個節點,並且返回鏈表的頭結點。
示例:
給定一個鏈表: 1->2->3->4->5, 和 n = 2.
當刪除了倒數第二個節點後,鏈表變爲 1->2->3->5.
說明:
給定的 n 保證是有效的。
進階:
你能嘗試使用一趟掃描實現嗎?
代碼:
/**
* 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(head==NULL||head->next==NULL)
return NULL;
ListNode *del,*temp;
int count=0;
del=head;
temp=head;
while(head->next!=NULL)
{
count++;
head=head->next;
if(count-n>0)
{
del=del->next;
}
}
if(n==1)
{
del->next=NULL;
}
else if(count<n)
{
temp=temp->next;
}
else
{
del->next=del->next->next;
}
return temp;
}
};