Intersection of Two Linked Lists

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

For example, the following two linked lists:

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.
Credits:
Special thanks to @stellari for adding this problem and creating all test cases.

SOLUTION 1:

1. 得到2个链条的长度。

2. 将长的链条向前移动差值(len1 - len2)

3. 两个指针一起前进,遇到相同的即是交点,如果没找到,返回null.

相当直观的解法。空间复杂度O(1), 时间复杂度O(m+n)

 public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
} int lenA = getLen(headA);
int lenB = getLen(headB); if (lenA > lenB) {
while (lenA > lenB) {
headA = headA.next;
lenA--;
}
} else {
while (lenA < lenB) {
headB = headB.next;
lenB--;
}
} while (headA != null) {
if (headA == headB) {
return headA;
}
headA = headA.next;
headB = headB.next;
} return null;
} public int getLen(ListNode node) {
int len = 0;
while (node != null) {
len++;
node = node.next;
}
return len;
}

2014.12.17 redo:

 /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
} ListNode cur = headA;
int len1 = getLen(headA);
int len2 = getLen(headB); int cnt = Math.abs(len1 - len2); // cut the longer list.
if (len1 > len2) {
while (cnt > 0) {
headA = headA.next;
cnt--;
}
} else {
while (cnt > 0) {
headB = headB.next;
cnt--;
}
} while (headA != null) {
if (headA == headB) {
return headA;
} headA = headA.next;
headB = headB.next;
} return null;
} public int getLen(ListNode head) {
int cnt = 0;
while (head != null) {
head = head.next;
cnt++;
} return cnt;
}
}

SOLUTION 2:

解完后,打开Leetcode的solution, 找到一个很巧妙的解法。其实与解法1相比应该快不了多少,但是写出来超有B格的。。

Two pointer solution (O(n+m) running time, O(1) memory):
Maintain two pointers pA and pB initialized at the head of A and B, respectively. Then let them both traverse through the lists, one node at a time.
When pA reaches the end of a list, then redirect it to the head of B (yes, B, that's right.); similarly when pB reaches the end of a list, redirect it the head of A.
If at any point pA meets pB, then pA/pB is the intersection node.
To see why the above trick would work, consider the following two lists: A = {1,3,5,7,9,11} and B = {2,4,9,11}, which are intersected at node '9'. Since B.length (=4) < A.length (=6), pB would reach the end of the merged list first, because pB traverses exactly 2 nodes less than pA does. By redirecting pB to head A, and pA to head B, we now ask pB to travel exactly 2 more nodes than pA would. So in the second iteration, they are guaranteed to reach the intersection node at the same time.
If two lists have intersection, then their last nodes must be the same one. So when pA/pB reaches the end of a list, record the last element of A/B respectively. If the two last elements are not the same one, then the two lists have no intersections.

主页君实现如下:

 public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
} ListNode pA = headA;
ListNode pB = headB; ListNode tailA = null;
ListNode tailB = null; while (true) {
if (pA == null) {
pA = headB;
} if (pB == null) {
pB = headA;
} if (pA.next == null) {
tailA = pA;
} if (pB.next == null) {
tailB = pB;
} //The two links have different tails. So just return null;
if (tailA != null && tailB != null && tailA != tailB) {
return null;
} if (pA == pB) {
return pA;
} pA = pA.next;
pB = pB.next;
}
}

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/list/GetIntersectionNode1.java

附一个链表大总结的链接:

http://weibo.com/3948019741/BseJ6ukI3

LeetCode: Intersection of Two Linked Lists 解题报告的更多相关文章

  1. 【LeetCode】160. Intersection of Two Linked Lists 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 双指针 栈 日期 题目地址:https://leet ...

  2. 【原创】leetCodeOj --- Intersection of Two Linked Lists 解题报告(经典的相交链表找交点)

    题目地址: https://oj.leetcode.com/problems/intersection-of-two-linked-lists/ 题目内容: Write a program to fi ...

  3. [LeetCode] 160. Intersection of Two Linked Lists 解题思路

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

  4. [LeetCode] Intersection of Two Linked Lists 求两个链表的交点

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

  5. LeetCode Intersection of Two Linked Lists

    原题链接在这里:https://leetcode.com/problems/intersection-of-two-linked-lists/ 思路:1. 找到距离各自tail 相同距离的起始List ...

  6. LeetCode——Intersection of Two Linked Lists

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

  7. [LeetCode] Intersection of Two Linked Lists 两链表是否相交

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

  8. 【LeetCode】206. Reverse Linked List 解题报告(Python&C++&java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 递归 日期 [LeetCode] 题目地址:h ...

  9. 【LeetCode】234. Palindrome Linked List 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

随机推荐

  1. python之函数用法basestring

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法basestring #http://www.cnblogs.com/oneday/a ...

  2. IP共享重新验证

    大家在进入共享机器的时候,在运行窗口中输入了 \\IP 然后会有账户和密码验证, 有时为了方便选择了记忆密码账号,这样下次就不会再验证了. 但是,有时你当时输入的账户没有你需要打开的某个文件的权限,就 ...

  3. 将Gradle项目公布到maven仓库

    将Gradle项目公布到maven仓库 1 Gradle简单介绍 1.1 Ant.Maven还是Gradle? 1.1.1 Ant和Maven介绍 全称为Apache Maven,是一个软件(特别是J ...

  4. Mac 通过活动监视器关闭卡死进程

    前言: 心好累,Lantern太不省事了 之前装过之后,就设定了开启自启动,搞得我上网都受影响(这玩意,qq没事,但是网易云之类的一些软件上网都不行了...就是这玩意搞的鬼) 没办法,点击关闭吧... ...

  5. 入门Nginx

    一.正向代理和反向代理 正向代理举例:翻越万里长城去游览墙外的景色 反向代理举例:负载均衡 正向代理和反向代理涉及三个主体: 请求方 代理 被请求方 正向代理中,代理跟请求方是一家子,请求方说要啥,代 ...

  6. Hibernate学习备忘

    1.关于Hibernate异常: org.hibernate.service.jndi.JndiException: Error parsing JNDI name   刚接触Hibernate,调试 ...

  7. 漫谈Github与开源,Git介绍以及Git的思想和基本工作原理 Git工作流程

    漫谈Github与开源 文字亮点: 为什么这些优秀的工程师会开源自己的项目? 因为开源是一种精神. 无数的软件开发者苦心积虑保护自己的代码不被破解,而还是被聪明绝顶的脚本小子破解了,但破解无数软件的脚 ...

  8. 【转】一个对 Dijkstra 的采访视频

    一个对 Dijkstra 的采访视频 (也可以访问 YouTube 或者从源地址下载 MPEG1,300M) 之前在微博上推荐了一个对 Dijkstra 的采访视频,看了两遍之后觉得实在很好,所以再正 ...

  9. du和df命令的区别

    du和df命令都被用于获得文件系统大小的信息:df用于报告文件系统的总块数及剩余块数,du -s /<filesystem>用于报告文件系统使用的块数.但是,我们可以发现从df命令算出的文 ...

  10. Go TCP网路程序编写

    client和server程序编写 面向长连接的编程 http://files.cnblogs.com/files/yyx1-1/Go_TCP.7z