Interview----判断两个链表是否相交?
题目描述:
判断两个单链表是否相交?假设链表没有环。
假如链表有环呢?
1. 假如没有环
那么如果两个链表相交的话,必然最后的节点一定是同一个节点。所以只需要各自扫描一遍链表,找到最后一个节点,比较是否相同即可。
O ( M + N)
// version 1
// test whether two lists are intersected
// assume each list has no circle
bool IsIntersectedNoCircle(ListNode *lhs, ListNode *rhs)
{
if(lhs == NULL || rhs == NULL)
return false; ListNode *tail1(lhs);
for(; tail1->next; tail1 = tail1->next); ListNode *tail2(lhs);
for(; tail2->next; tail2 = tail2->next); return tail1 == tail2;
}
2. 可能有环
首先,如何判断是否有环?
采用快慢指针,一个指针一次走两步,一个指针一次走一步,如果链表有环的话,必然最后慢指针会赶上快指针。
复杂度同样是 O ( M + N)。
如果还要求求出 进入环的那个节点: 可以用两个指针,一个从链表head 出发,另一个从刚刚快慢指针的相遇点出发,速度相同。
可以证明,两指针必定在入口处第一次相遇。
// test whether list has a circle
// if true, return the enter node
// if not, return NULL
ListNode* HasCircle(ListNode *list)
{
if(list == NULL || list->next == NULL)
return NULL; // fast/slow pointer method
// if circled, slow pointer will catch up with fast one
ListNode *fast(list), *slow(list); while(fast)
{
fast = fast->next;
if(fast == NULL) return NULL;
fast = fast->next;
slow = slow->next; if(fast == slow)
break;
}
assert(fast == NULL || slow == fast); if(fast == NULL)
return NULL; // list definitely has a circle
// find the enter node
// fast and enter will meet at the enter node
ListNode *enter(list); while(enter != fast)
{
enter = enter->next;
fast = fast->next;
} return enter;
}
根据是否有环,可以分为以下三个 case:
case 1: 都没有环:已经分析
case 2: 都有环: 注意到如果相交,这两个环必定是一模一样的。所以,只要判断是否有一个节点在另一个环中即可。
case 3: 一个有环,一个没有环: 一定不相交
// version 2
// assume lists may have a circle inside
bool IsIntersectedCircle(ListNode *lhs, ListNode *rhs)
{
ListNode *enter1(NULL), *enter2(NULL); enter1 = HasCircle(lhs);
enter2 = HasCircle(rhs); // case 1: both lists have no circles
if(enter1 == NULL && enter2 == NULL)
{
return IsIntersectedNoCircle(lhs, rhs);
}
// case 2: each have a circle
else if(enter1 && enter2)
{
ListNode *node(enter1->next); while(node != enter1 && node != enter2){
node = node->next;
}
return node == enter2;
}
// case 3: one has a circle, while the other not
else
{
return false;
}
}
完整代码如下:
// copyright @ L.J.SHOU Feb.27, 2014
// test whether two lists are intersected
#include <iostream>
#include <cassert>
using namespace std; struct ListNode{
int val;
ListNode *next;
ListNode(int x)
:val(x), next(NULL){}
}; ListNode* HasCircle(ListNode*);
bool IsIntersectedCircle(ListNode*, ListNode*); // version 1
// test whether two lists are intersected
// assume each list has no circle
bool IsIntersectedNoCircle(ListNode *lhs, ListNode *rhs)
{
if(lhs == NULL || rhs == NULL)
return false; ListNode *tail1(lhs);
for(; tail1->next; tail1 = tail1->next); ListNode *tail2(lhs);
for(; tail2->next; tail2 = tail2->next); return tail1 == tail2;
} // version 2
// assume lists may have a circle inside
bool IsIntersectedCircle(ListNode *lhs, ListNode *rhs)
{
ListNode *enter1(NULL), *enter2(NULL); enter1 = HasCircle(lhs);
enter2 = HasCircle(rhs); // case 1: both lists have no circles
if(enter1 == NULL && enter2 == NULL)
{
return IsIntersectedNoCircle(lhs, rhs);
}
// case 2: each have a circle
else if(enter1 && enter2)
{
ListNode *node(enter1->next); while(node != enter1 && node != enter2){
node = node->next;
}
return node == enter2;
}
// case 3: one has a circle, while the other not
else
{
return false;
}
} // test whether list has a circle
// if true, return the enter node
// if not, return NULL
ListNode* HasCircle(ListNode *list)
{
if(list == NULL || list->next == NULL)
return NULL; // fast/slow pointer method
// if circled, slow pointer will catch up with fast one
ListNode *fast(list), *slow(list); while(fast)
{
fast = fast->next;
if(fast == NULL) return NULL;
fast = fast->next;
slow = slow->next; if(fast == slow)
break;
}
assert(fast == NULL || slow == fast); if(fast == NULL)
return NULL; // list definitely has a circle
// find the enter node
// fast and enter will meet at the enter node
ListNode *enter(list); while(enter != fast)
{
enter = enter->next;
fast = fast->next;
} return enter;
} // destroy list
ListNode* Destroy(ListNode *list)
{
ListNode *next(NULL); while(list)
{
next = list->next;
delete list;
list = next;
} return NULL;
} int main(void)
{
ListNode *list(NULL); // testing case 1: both have no circles
list = new ListNode(1);
list->next = new ListNode(2);
list->next->next = new ListNode(3); ListNode *list2 = list->next;
cout << IsIntersectedCircle(list, list2) << endl; // testing case 2: both have circles
list2 = new ListNode(1);
list2->next = new ListNode(2);
list2->next->next = list->next; list->next->next->next = list->next;
cout << IsIntersectedCircle(list, list2) << endl; list->next->next->next = NULL;
list2->next->next = NULL; // testing case 3: only one has a circle
list->next->next->next = list->next;
cout << IsIntersectedCircle(list, list2) << endl;
list->next->next->next = NULL; list = Destroy(list);
list2 = Destroy(list2); return 0;
}
Interview----判断两个链表是否相交?的更多相关文章
- Oracle判断两个时间段是否相交
SQL中常常要判断两个时间段是否相交,该如何判断呢?比如两个时间段(S1,E1)和(S2,E2).我最先想到的是下面的方法一.方法一:(S1 BETWEEN S2 AND E2) OR (S2 BET ...
- IT公司100题-7-判断两个链表是否相交
问题:有一个单链表,其中可能有一个环,也就是某个节点的next指向的是链表中在它之前的节点,这样在链表的尾部形成一环.1.如何判断一个链表是不是这类链表? 问题扩展:1.如果链表可能有环呢?2.如果需 ...
- C# 判断两条直线是否相交
直接上代码,过程不复杂 /// <summary> /// 判断两条线是否相交 /// </summary> /// <param name="a"& ...
- PHP判断两个矩形是否相交
<?php $s = is_rect_intersect(1,2,1,2,4,5,0,3); var_dump($s); /* 如果两个矩形相交,那么矩形A B的中心点和矩形的边长是有一定关系的 ...
- C# 判断两个矩形是否相交
源代码 public bool JudgeRectangleIntersect(double RecAleftX, double RecAleftY, double RecArightX, doubl ...
- cocos2d-x 判断两条直线是否相交
bool GraphicsUtil::linesCross(b2Vec2 v0, b2Vec2 v1, b2Vec2 t0, b2Vec2 t1, b2Vec2 &intersectionPo ...
- Cracking the Coding Interview:: 寻找有环链表的环路起始节点
给定一个有环链表,实现一个算法返回环路的开头节点. 这个问题是由经典面试题-检测链表是否存在环路演变而来.这个问题也是编程之美的判断两个链表是否相交的扩展问题. 首先回顾一下编程之美的问题. 由于如果 ...
- 如何判断单链表是否存在环 & 判断两链表是否相交
给定一个单链表,只给出头指针h: 1.如何判断是否存在环? 2.如何知道环的长度? 3.如何找出环的连接点在哪里? 4.带环链表的长度是多少? 解法: 1.对于问题1,使用追赶的方法,设定两个指针sl ...
- You can Solve a Geometry Problem too (hdu1086)几何,判断两线段相交
You can Solve a Geometry Problem too Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/3276 ...
随机推荐
- CSS3:不可思议的border属性&Web字体图标Font Awesome
CSS3:不可思议的border属性 转载至——译文:不可思议的CSS border属性 原文:Magic of CSS border property Web字体图标Font Awesome 转载 ...
- Unique Paths II [LeetCode]
Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How m ...
- win7_oracle11g_64位连接32位PLSQL_Developer
工具/原料 已经装好的64位Oracle数据库 window7_64位的操作系统 PLSQL_Developer 9.0以上版本(目前只有32位的):下面有下载连接! 官方的 instantcli ...
- word2013设置页面边框
如图:
- Spring MVC Controller中解析GET方式的中文参数会乱码的问题(tomcat如何解码)
Spring MVC Controller中解析GET方式的中文参数会乱码的问题 问题描述 在工作上使用突然出现从get获取中文参数乱码(新装机器,tomcat重新下载和配置),查了半天终于找到解决办 ...
- HTTP 错误 500.22 - Internal Server Error 检测到在集成的托管管道模式下不适用的 ASP.NET 设置
答案:在将WebDataHelper升级到VS2013是出现的这个错误,这个程序使用了URL重写的技术, 解决方法是:需要将重写的配置,迁移到system.webServer配置节中
- JS解析json数据并将json字符串转化为数组的实现方法
json数据在ajax实现异步交互时起到了很重要的作用,他可以返回请求的数据,然后利用客户端的js进行解析,这一点体现出js的强大,本文介绍JS解析json数据并将json字符串转化为数组的实现方法, ...
- qml package 的使用
什么时候使用这个.就是多个view使用同一个deleagte的时候. The Package class is used in conjunction with VisualDataModel to ...
- Js笔试题之parseInt()和.map()
parseInt()的几个例子 var b = parseInt("01"); alert("b="+b); var c = parseInt("09 ...
- Android窃取用户信息新思路
0×01 我们能得到哪些android手机上的app敏感信息手机上的app敏感信息◦通讯录,通讯记录,短信◦各种app的帐号密码,输入信息资料等◦各种影音资料,照片资料◦等等0×02 我们有哪些方法 ...