LeetCode#160 Intersection of Two Linked Lists
2015-07-20 16:03
309 查看
Problem Definition:Write a program to find the node at which the intersection of two singly linked lists begins.For example, the following two linked lists:
begin to intersect at node c1.Notes:If the two linked lists have no intersection at all, return
Solution 2:利用同样的原理,不同的解释。1)同时遍历两个链表。ha遍历headA所指代链表,hb遍历headB所指代链表。2)当ha到达链表尾时,将其指向headB,继续遍历;当hb到达链表尾时,将其指向headA,继续遍历。3)当ha==hb时,返回ha。 看下面的栗子:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
begin to intersect at node c1.Notes:If the two linked lists have no intersection at all, return
null.The linked lists must retain their original structure after the function returns.You may assume there are no cycles anywhere in the entire linked structure.Your code should preferably run in O(n) time and use only O(1) memory.Solution 1: Seems a little bit long, but it's straightforward.
def getIntersectionNode( headA, headB): l1,l2=0,0 ha,hb=headA,headB while ha!=None: ha=ha.next l1+=1 while hb!=None: hb=hb.next l2+=1 ha,hb=headA,headB #throwback if l1>l2: sub=l1-l2 while sub>0: ha=ha.next sub-=1 else: sub=l2-l1 while sub>0: hb=hb.next sub-=1 while ha!=hb: ha=ha.next hb=hb.next return ha
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
Solution 2:利用同样的原理,不同的解释。1)同时遍历两个链表。ha遍历headA所指代链表,hb遍历headB所指代链表。2)当ha到达链表尾时,将其指向headB,继续遍历;当hb到达链表尾时,将其指向headA,继续遍历。3)当ha==hb时,返回ha。 看下面的栗子:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
ha从a1开始走到c3,然后指向b1。此时hb正指向c3。
下一时刻,ha到达b2,而hb到达a1。如此便达到了类似前一种解法中的(使得两链表从到末节点距离相同的两个节点开始遍历)效果
继续遍历就会到达c1。在以上过程中,每一步(ha和hb都移动后)都判断ha==hb,一旦成立则立即返回。
因此会有以下不同情况
1)两表有公共子链,但两表不等长,则在第二轮遍历时会找到交叉节点
2)两表有公共子链,且两表等长,则在第一轮遍历时就能找到交叉节点
3)两表没有公共子链,则在第一轮或者第二轮遍历中同时变为空,相等,返回空代码:
def getIntersectionNode( headA, headB): ha,hb=headA,headB while ha!=hb: ha=ha.next if ha!=None else headB hb=hb.next if hb!=None else headA return ha
相关文章推荐
- linux内核数据结构之kfifo
- 陈力:传智播客古代 珍宝币 泡泡龙游戏开发第十三讲:盒子的定位实例
- qsort
- poj 1845
- ajax学习过程
- 南阳oj 数据结构 括号配对 题目2 NYOJ
- 杭电 2002 计算球体积
- hdu 2444The Accomodation of Students 二分图判定+找最大匹配
- [Linux].vimrc配置
- HTML5游戏总结:分辨率对游戏布局设计的影响
- 通过SQL Server Profiler来监视分析死锁
- Python Static Method
- jquery animate 制作简单弹幕
- 国内代码托管平台(Git)
- NOIP2012-普及组复赛-第二题-寻宝
- CTreeCtrl
- Eclipse快捷键 10个最有用的快捷键
- 关于扫雷游戏学习笔记(二)
- linux svn cmd
- 网络信息安全