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

For example, the following two linked lists:

  1. A: a1 a2

  2. c1 c2 c3

  3. 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.

求两个链表的交点,要求Time: O(n), Space: O(1)

解法1:交点最早可能出现在短链表的第一个节点,后面的节点两个链表一样。所以,长链表的比短链表开始多出的那些就没用。求出两个链表的长度差值,把较长的链表向后移动这个差值,变成一样长。然后在一个一个的比较。

解法2: 双指针,用两个指针pA和pB分别指向链表A和B。然后让它们分别遍历整个链表,每步一个节点。当pA到达链表末尾时,让它指向B的头节点(没错,是B);类似的当pB到达链表末尾时,重新指向A的头节点。如果pA在某一点与pB相遇,则pA/pB就是交集开始的节点。

Java: Solution 1

  1. public class Solution {
  2. public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
  3. if (headA == null || headB == null) return null;
  4. int lenA = getLength(headA), lenB = getLength(headB);
  5. if (lenA > lenB) {
  6. for (int i = 0; i < lenA - lenB; ++i) headA = headA.next;
  7. } else {
  8. for (int i = 0; i < lenB - lenA; ++i) headB = headB.next;
  9. }
  10. while (headA != null && headB != null && headA != headB) {
  11. headA = headA.next;
  12. headB = headB.next;
  13. }
  14. return (headA != null && headB != null) ? headA : null;
  15. }
  16. public int getLength(ListNode head) {
  17. int cnt = 0;
  18. while (head != null) {
  19. ++cnt;
  20. head = head.next;
  21. }
  22. return cnt;
  23. }
  24. }

Java: Solution 2

  1. public class Solution {
  2. public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
  3. if (headA == null || headB == null) return null;
  4. ListNode a = headA, b = headB;
  5. while (a != b) {
  6. a = (a != null) ? a.next : headB;
  7. b = (b != null) ? b.next : headA;
  8. }
  9. return a;
  10. }
  11. } 

Python:

  1. class Solution:
  2. # @param two ListNodes
  3. # @return the intersected ListNode
  4. def getIntersectionNode(self, headA, headB):
  5. if headA is None or headB is None:
  6. return None
  7.  
  8. pa = headA # 2 pointers
  9. pb = headB
  10.  
  11. while pa is not pb:
  12. # if either pointer hits the end, switch head and continue the second traversal,
  13. # if not hit the end, just move on to next
  14. pa = headB if pa is None else pa.next
  15. pb = headA if pb is None else pb.next
  16.  
  17. return pa # only 2 ways to get out of the loop, they meet or the both hit the end=None
  18.  
  19. # the idea is if you switch head, the possible difference between length would be countered.
  20. # On the second traversal, they either hit or miss.
  21. # if they meet, pa or pb would be the node we are looking for,
  22. # if they didn't meet, they will hit the end at the same iteration, pa == pb == None, return either one of them is the same,None

Python: wo

  1. class Solution(object):
  2. def getIntersectionNode(self, headA, headB):
  3. if not headA or not headB:
  4. return None
  5.  
  6. a, b = headA, headB
  7. while a != b:
  8. a = a.next if a else headB
  9. b = b.next if b else headA
  10.  
  11. return a  

Python: Solution 1

  1. class Solution(object):
  2. def getIntersectionNode(self, headA, headB):
  3. lenA = self.getListLen(headA)
  4. lenB = self.getListLen(headB)
  5. if lenA > lenB:
  6. for i in range(lenA - lenB):
  7. headA = headA.next
  8. elif lenA < lenB:
  9. for i in range(lenB - lenA):
  10. headB = headB.next
  11. while headA != headB:
  12. headA, headB = headA.next, headB.next
  13. return headA
  14.  
  15. def getListLen(self, head):
  16. length = 0
  17. while head:
  18. length += 1
  19. head = head.next
  20. return length 

Python: Solution 2

  1. class ListNode:
  2. def __init__(self, x):
  3. self.val = x
  4. self.next = None
  5.  
  6. class Solution:
  7. # @param two ListNodes
  8. # @return the intersected ListNode
  9. def getIntersectionNode(self, headA, headB):
  10. curA, curB = headA, headB
  11. begin, tailA, tailB = None, None, None
  12.  
  13. # a->c->b->c
  14. # b->c->a->c
  15. while curA and curB:
  16. if curA == curB:
  17. begin = curA
  18. break
  19.  
  20. if curA.next:
  21. curA = curA.next
  22. elif tailA is None:
  23. tailA = curA
  24. curA = headB
  25. else:
  26. break
  27.  
  28. if curB.next:
  29. curB = curB.next
  30. elif tailB is None:
  31. tailB = curB
  32. curB = headA
  33. else:
  34. break
  35.  
  36. return begin  

C++:

  1. class Solution {
  2. public:
  3. ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
  4. if (!headA || !headB) return NULL;
  5. int lenA = getLength(headA), lenB = getLength(headB);
  6. if (lenA < lenB) {
  7. for (int i = 0; i < lenB - lenA; ++i) headB = headB->next;
  8. } else {
  9. for (int i = 0; i < lenA - lenB; ++i) headA = headA->next;
  10. }
  11. while (headA && headB && headA != headB) {
  12. headA = headA->next;
  13. headB = headB->next;
  14. }
  15. return (headA && headB) ? headA : NULL;
  16. }
  17. int getLength(ListNode* head) {
  18. int cnt = 0;
  19. while (head) {
  20. ++cnt;
  21. head = head->next;
  22. }
  23. return cnt;
  24. }
  25. };

C++:

  1. class Solution {
  2. public:
  3. ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
  4. if (!headA || !headB) return NULL;
  5. ListNode *a = headA, *b = headB;
  6. while (a != b) {
  7. a = a ? a->next : headB;
  8. b = b ? b->next : headA;
  9. }
  10. return a;
  11. }
  12. };

 

类似题目:

[LeetCode] 349. Intersection of Two Arrays 两个数组相交

[LeetCode] 350. Intersection of Two Arrays II 两个数组相交II

   

All LeetCode Questions List 题目汇总

[LeetCode] 160. Intersection of Two Linked Lists 求两个链表的交集的更多相关文章

  1. ✡ leetcode 160. Intersection of Two Linked Lists 求两个链表的起始重复位置 --------- java

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

  2. 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 ...

  3. [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 ...

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

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

  5. [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 ...

  6. [LeetCode]160.Intersection of Two Linked Lists(2个链表的公共节点)

    Intersection of Two Linked Lists Write a program to find the node at which the intersection of two s ...

  7. [LeetCode]160. Intersection of Two Linked Lists判断交叉链表的交点

    方法要记住,和判断是不是交叉链表不一样 方法是将两条链表的路径合并,两个指针分别从a和b走不同路线会在交点处相遇 public ListNode getIntersectionNode(ListNod ...

  8. 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 ...

  9. Java for 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 ...

随机推荐

  1. 基于appium快速实现H5自动化测试

    一.下载Appium-Server及库文件 库文件:jar包:java-client-3.1.0.jar Appium-Server:Appium服务器: 注:Appium包含客户端和服务端,客户端就 ...

  2. 通俗理解word2vec的训练过程

    https://www.leiphone.com/news/201706/eV8j3Nu8SMqGBnQB.html https://blog.csdn.net/dn_mug/article/deta ...

  3. 与你一起学习MS Project——基础篇:Project基础应用

    为了更清晰容易地熟悉掌握Project的基础应用,我们在基础篇中一起来学习掌握在Project中如何做进度计划.资源计划.成本计划以及跟踪项目的执行情况并生成所需的项目报表. 一.进度计划 这里,首先 ...

  4. CentOS7.6安装docker最新版

    注意Centos7.4系统以下需要升级内核,否则会安装失败 yum install -y yum-utils device-mapper-persistent-data lvm2 yum-config ...

  5. get_template_part()调用自定义模板|wordpress函数

    我们在用wordpress开发主题的时候,可能需要调用一段固定的代码比如左侧菜单,这段代码会在主页.栏目页.文章页用到,如果直接写入每个页面模板是没有问题,但是如果要改左侧菜单一个链接那就要改三次,很 ...

  6. MSSQL 删除索引

    使用SSMS数据库管理工具删除索引 使用表设计器删除索引 表设计器可以删除任何类型的索引,本示例演示删除XML辅助索引,删除其他索引步骤相同. 1.连接数据库,选择数据库,展开数据库->选择数据 ...

  7. ssh集成

    导入pom依赖 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w ...

  8. [HAOI2015]树上染色 树状背包 dp

    #4033. [HAOI2015]树上染色 Description 有一棵点数为N的树,树边有边权.给你一个在0~N之内的正整数K,你要在这棵树中选择K个点,将其染成黑色,并 将其他的N-K个点染成白 ...

  9. SQL基础-创建新的输出字段

    一.创建新的输出字段 1.建表.插数据 ### CREATE TABLE `t_stock_trans_dtl` ( `trans_id` varchar(100) NOT NULL COMMENT ...

  10. 【叔小生】JavaScript进阶篇

    如何插入JS JS基础语法 语法.函数.方法 提取字符串substring() substring() 方法用于提取字符串中介于两个指定下标之间的字符. <!DOCTYPE HTML> & ...