Lintcode380 Intersection of Two Linked Lists solution 题解

Posted ccccnnnblog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lintcode380 Intersection of Two Linked Lists solution 题解相关的知识,希望对你有一定的参考价值。

【题目描述】

Write a program to find the node at which the intersection of two singly linked lists begins.

Notice:

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.

请写一个程序,找到两个单链表最开始的交叉节点。

【注】1、如果两个链表没有交叉,返回null。

2、在返回结果后,两个链表仍须保持原有的结构。

3、可假定整个链表结构中没有循环。

【题目链接】

www.lintcode.com/en/problem/intersection-of-two-linked-lists/

【题目解析】

这道题可以使用双指针法。

维护两个指针pA和pB,初始分别指向A和B。然后让它们分别遍历整个链表,每步一个节点。

当pA到达链表末尾时,让它指向B的头节点(没错,是B);类似的当pB到达链表末尾时,重新指向A的头节点。

如果pA在某一点与pB相遇,则pA/pB就是交点。

下面来看下为什么这个算法可行,考虑两个链表:A = {1,3,5,7,9,11} B = {2,4,9,11},它们的交点是节点‘9‘。由于B的长度是4 小于 A的长度6,pB会首先到达链表的末尾,由于pB比pA恰好少走2个节点。通过把pB指向A的头,把pA指向B的头,我们现在让pB比pA恰好多走2个节点。所以在第二轮,它们可以保证同时在交点相遇。

如果两个链表有交点,则它们的最后一个节点一定是同一个节点。所以当pA/pB到达链表末尾时,分别记录下A和B的最后一个节点。如果两个链表的末尾节点不一致,说明两个链表没有交点。

【参考答案】

www.jiuzhang.com/solutions/intersection-of-two-linked-lists/

以上是关于Lintcode380 Intersection of Two Linked Lists solution 题解的主要内容,如果未能解决你的问题,请参考以下文章

3 - Two Pointers Algorithm

[LintCode] Intersection of Two Arrays 两个数组相交

[LintCode] Intersection of Two Arrays II 两个数组相交之二

[LintCode] Intersection of Two Linked Lists 求两个链表的交点

LintCode 数组

罗技k380连不上win10,罗技k380电脑搜索不到