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.

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

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

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

Java: Solution 1

public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) return null;
int lenA = getLength(headA), lenB = getLength(headB);
if (lenA > lenB) {
for (int i = 0; i < lenA - lenB; ++i) headA = headA.next;
} else {
for (int i = 0; i < lenB - lenA; ++i) headB = headB.next;
}
while (headA != null && headB != null && headA != headB) {
headA = headA.next;
headB = headB.next;
}
return (headA != null && headB != null) ? headA : null;
}
public int getLength(ListNode head) {
int cnt = 0;
while (head != null) {
++cnt;
head = head.next;
}
return cnt;
}
}

Java: Solution 2

public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) return null;
ListNode a = headA, b = headB;
while (a != b) {
a = (a != null) ? a.next : headB;
b = (b != null) ? b.next : headA;
}
return a;
}
} 

Python:

class Solution:
# @param two ListNodes
# @return the intersected ListNode
def getIntersectionNode(self, headA, headB):
if headA is None or headB is None:
return None pa = headA # 2 pointers
pb = headB while pa is not pb:
# if either pointer hits the end, switch head and continue the second traversal,
# if not hit the end, just move on to next
pa = headB if pa is None else pa.next
pb = headA if pb is None else pb.next return pa # only 2 ways to get out of the loop, they meet or the both hit the end=None # the idea is if you switch head, the possible difference between length would be countered.
# On the second traversal, they either hit or miss.
# if they meet, pa or pb would be the node we are looking for,
# 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

class Solution(object):
def getIntersectionNode(self, headA, headB):
if not headA or not headB:
return None a, b = headA, headB
while a != b:
a = a.next if a else headB
b = b.next if b else headA return a  

Python: Solution 1

class Solution(object):
def getIntersectionNode(self, headA, headB):
lenA = self.getListLen(headA)
lenB = self.getListLen(headB)
if lenA > lenB:
for i in range(lenA - lenB):
headA = headA.next
elif lenA < lenB:
for i in range(lenB - lenA):
headB = headB.next
while headA != headB:
headA, headB = headA.next, headB.next
return headA def getListLen(self, head):
length = 0
while head:
length += 1
head = head.next
return length 

Python: Solution 2

class ListNode:
def __init__(self, x):
self.val = x
self.next = None class Solution:
# @param two ListNodes
# @return the intersected ListNode
def getIntersectionNode(self, headA, headB):
curA, curB = headA, headB
begin, tailA, tailB = None, None, None # a->c->b->c
# b->c->a->c
while curA and curB:
if curA == curB:
begin = curA
break if curA.next:
curA = curA.next
elif tailA is None:
tailA = curA
curA = headB
else:
break if curB.next:
curB = curB.next
elif tailB is None:
tailB = curB
curB = headA
else:
break return begin  

C++:

class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (!headA || !headB) return NULL;
int lenA = getLength(headA), lenB = getLength(headB);
if (lenA < lenB) {
for (int i = 0; i < lenB - lenA; ++i) headB = headB->next;
} else {
for (int i = 0; i < lenA - lenB; ++i) headA = headA->next;
}
while (headA && headB && headA != headB) {
headA = headA->next;
headB = headB->next;
}
return (headA && headB) ? headA : NULL;
}
int getLength(ListNode* head) {
int cnt = 0;
while (head) {
++cnt;
head = head->next;
}
return cnt;
}
};

C++:

class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (!headA || !headB) return NULL;
ListNode *a = headA, *b = headB;
while (a != b) {
a = a ? a->next : headB;
b = b ? b->next : headA;
}
return a;
}
};

 

类似题目:

[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. Unity进阶:行为树 01

    版权申明: 本文原创首发于以下网站: 博客园『优梦创客』的空间:https://www.cnblogs.com/raymondking123 优梦创客的官方博客:https://91make.top ...

  2. SQL模糊查询的四种匹配模式

    执行数据库查询时,有完整查询和模糊查询之分,一般模糊语句如下: SELECT 字段 FROM 表 WHERE 某字段 Like 条件 一.四种匹配模式 关于条件,SQL提供了四种匹配模式: 1.% 表 ...

  3. 微信小程序~页面跳转和路由

    一个小程序拥有多个页面,我们可以通过wx.navigateTo推入一个新的页面,如图3-6所示,在首页使用2次wx.navigateTo后,页面层级会有三层,我们把这样的一个页面层级称为页面栈.

  4. 使用gitlab下载代码(附常用命令)

    Git是现在很多人常用的代码管理工具,这里有一些常用的命令详解,本人接触也不是很久,若有错误,请在评论指出,谢谢. 若计算机中没有安装GIT,可自行查找安装教程,十分简便. ①首先,我们需要下载项目, ...

  5. webview-h5页面刷新

    问题:webview 缓存了index.html页面:浏览器缓存了子页面.解决方案:网页链接后添加时间戳. 第一:避免webView缓存]在service.vue中,给url后边添加时间戳 第二:避免 ...

  6. Alpha版本1之后的成绩汇总

    作业要求 1.作业内容: 作业具体要求及评分标准的链接 2.评分细则 •给出开头和团队成员列表(10’) •给出发布地址以及安装手册(20’) •给出测试报告(40’) •给出项目情况总结(30’) ...

  7. ZOJ - 3265: Strange Game (优化 二分图匹配)

    pro:有一个长度为N的数组a[i],要求选择k[i]>0,使得b[i]=a[i]^k[i]%M中出现的不同数最多.N<=200, M<=1e9: sol:a^x%p的个数的有限的, ...

  8. BZOJ1499: 瑰丽华尔兹(单调队列)

    pro: 给出一个n*m的地图,刚开始人在(x,y),每次给出一段区间(l,r,t),表示在时间[l,r]内,可以使人向4个方向(t)移动一格,或者不动.求最大可以移动多少格. sol: 考虑每一列( ...

  9. PHP——数组根据某一键值合并

    前言 其实要实现很简单直接foreach,再根据PHP中数组的特性就可以轻松实现. 步骤 这是源数据的格式 $info = [ [ "gname" => "特别关心 ...

  10. 使用Patroni和HAProxy创建高可用的PostgreSQL集群

    操作系统:CentOS Linux release 7.6.1810 (Core) node1:192.168.216.130 master node2:192.168.216.132 slave n ...