标签:
first:
class Solution
{
public:
ListNode* removeNthFromEnd(ListNode* head, int n)
{
if (head==NULL)
{
return NULL;
}
ListNode* ptmp = head;
ListNode* pre = NULL;
int count = 1;
while (ptmp->next != NULL)
{
pre = ptmp;
ptmp = ptmp->next;
count++;
}
if (n==1)
{
pre->next = NULL;
delete ptmp;
}
else
{
// 从前往后遍历
ptmp = head;
pre = NULL;
int tmp = count-n+1;
if (tmp<0)
{
return NULL;
}
if (tmp == 1)
{
head == NULL;
delete ptmp;
}
int num = 1;
while (ptmp)
{
num++;
pre = ptmp;
ptmp=ptmp->next;
if (num == tmp)
{
break;
}
}
pre->next = ptmp->next;
delete ptmp;
}
return head;
}
};
second: (AC)
class Solution
{
public:
ListNode* removeNthFromEnd(ListNode* head, int n)
{
if (head==NULL || n==0)
{
return NULL;
}
ListNode helper(0);
helper.next = head;
ListNode* fptr = head;
ListNode* tptr = head;
ListNode* ppre = &helper;
while (n>0)
{
fptr = fptr->next;
n--;
}
while (fptr)
{
ppre = tptr;
tptr = tptr->next;
fptr = fptr->next;
}
ppre->next = tptr->next;
return helper.next;
}
};
第一次是想先遍历一次求出长度,然后再遍历一次找出倒数第n个节点删除, 但是不能被ac, 然后上网看了一下别人的方法。。。短小精悍,通过双指针实现,第一个指针先往后移n位, 然后两个指针再同步移动,第一个指针为空时停止移动。 还借助了一个额外节点来处理删除节点是头指针的情况, 我果然是渣渣, 每次都想的最笨的方法, 而且写的代码又烂,让我静一静(\再见)
版权声明:本文为博主原创文章,未经博主允许不得转载。
leetcode Remove Nth Node From End of List
标签:
原文地址:http://blog.csdn.net/nizhannizhan/article/details/46964745