在单向链表中如何快速查到倒数第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;
}
};
操作方法和步骤:
(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;
}
};
相关文章推荐
- .LEFT()and RIGHT()函数
- iOS KVC 和 KVO 简单介绍
- 常规测试方法
- 产品、服务和解决方案的区别是什么?
- 零碎知识点
- 【Unity】1.2 HelloWorld--测试桌面和Android游戏能否正常运行
- 二、2.4版本以后的apache的安装
- C#考题字符串
- static详解
- Md5使用详解
- Tomcat, Ant安装
- tableView的总结
- JS触发file类型Input的onclick()
- 《嵌入式怎么学?新人十问及解答》
- win7 64位旗舰版系统
- 338. Counting Bits
- springmvc+mybatis
- 使用libvirt创建虚拟机,虚拟机的配置文件内容
- synchronized静态同步方法与非静态同步方法,同步语句块
- 面试题:看数字找规律