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 ...
随机推荐
- 高性能Web服务端 PHP vs Node.js vs Nginx-Lua 的对比分析
1. ngx_lua nodejs php 比较 我在研究一阵子ngx_lua之后发现lua语法和js真的很像,同时ngx_lua模型也是单线程的异步的事件驱动的,工作原理和nodejs相同,代码甚至 ...
- C线程同步/异步
#include<windows.h> #include<stdio.h> #include<string.h> //#include <afxmt.h> ...
- 《JavaScript权威指南》读书笔记(三)
日期:2015-12-05 浏览器location和history: replace不会显示历史,location会: history对象脚本不能真正访问,但支持三种方法:back().foward( ...
- Linux Bash代码 利用for循环实现命令的多次执行
Linux Bash代码 [yuanhao15@lu01 libsvm-rank-2.81]$ for ((i=0; i<=19; i++)) do ./svm-train -s 5 -c 10 ...
- Ubuntu 13.10 Broadcom BCM4313问题
开始找不到无线网卡,后来不知道怎么就出来了,但是速度很慢.用下面的方法解决的(我也不知道哪条命令起的作用,反正现在正常了): sudo apt-get remove --purge bcmwl-ker ...
- swift 开眼今日精选
swift 开眼今日精选 import UIKit class TodayController: UITableViewController { vararray =NSMutableArray() ...
- FLASH AS 不显示中文
我修改一个as游戏,发现公告显示不了,整整折腾了2天. flash TextField 汉字不显示,英文会显示,如果是汉字夹杂数字,只把数字显示了,汉字被忽略了. 有人说嵌入字体,网上一搜索,好麻 ...
- Jmeter简单测试elasticsearch服务器
入门知识: Jmeter是一个非常好用的压力测试工具. Jmeter用来做轻量级的压力测试,非常合适,只需要十几分钟,就能把压力测试需要的脚本写好. 顾名思义:压力测试,就是 被测试的系统,在一定 ...
- JAVA传智 DAY1复习
Java平台: Java API JVM 特点:可跨平台 Java运行机制: 编译(javac.exe) 运行(java.exe) J ...
- 4通用Makefile编写
a.c #include<stdio.h> #include "a.h" int main() { printf("hello world\n"); ...