您的位置:首页 > 其它

在单向链表中如何快速查到倒数第n个节点 这简直是一种神奇的思路!!!!leetcode 删除倒数第n个节点

2016-03-23 16:06 507 查看
在单向链表中如何快速查到倒数第n个节点?

操作方法和步骤:

(1)定义2个指针p1,p2。

(2)使用循环让p2指向顺数第n个节点,同时p1指向第头结点;

(3)然后,p1和p2同时移动,直到p2指向NULL,此时p1应该指向倒数第n个节点。
19. Remove Nth Node From End of List

方法一:
<span style="font-family:SimHei;font-size:18px;">/**
* 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) {
int k=0;
ListNode *p=head;
while(p)
{
k++;
p=p->next;
}

if(head==NULL || head->next==NULL)
return NULL;
else if(head->next->next==NULL)
{
if(n==1)
head->next=NULL;
if(n==2)
head=head->next;
return head;
}
//有三个以上节点 要用到三个指针
else
{
ListNode *pre=head;
//ListNode *cur=pre->next;
if((k-n+1)==1)
{ pre = pre->next;
return pre;
}
for(int i=2;i<=(k-n);i++)
{
pre=pre->next;
}
pre->next=pre->next->next;
return head;
}

}
};</span>方法二: 真的好神奇
class Solution{
public:
ListNode* removeNthFromEnd(ListNode* head, int n){
ListNode *cur=head;
ListNode *pre=head;
for(int i=0;i<n;i++)
{
cur=cur->next;
}
if(!cur)
{
head=head->next;
return head;
}
while(cur->next)
{
pre=pre->next;
cur=cur->next;
}
pre->next=pre->next->next;
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: