您的位置:首页 > 其它

Intersection of Two Linked Lists

2016-03-11 10:37 225 查看


160. Intersection of Two Linked Lists

My Submissions

Question

Total Accepted: 65866 Total
Submissions: 218868 Difficulty: Easy

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.

双指针法 pa, pb

遍历链表A,记录其长度lengthA,遍历链表B,记录其长度lengthB。

因为两个链表的长度可能不相同,比如题目所给的case,lengthA=5,lengthB=6,则作差得到 lengthB- lengthA=1,将指针pb从链表B的首节点开始走1步,即指向了第二个节点,pa指向链表A首节点,然后它们同时走,每次都走一步,当它们相等时,就是交集的节点。

时间复杂度O(lengthA+lengthB),空间复杂度O(1)。双指针法的代码如下:

/**
* Created by jason on 2016/3/11.
*/
class Solution75 {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) return null;
ListNode pa = headA;
ListNode pb = headB;
int lengthA=0, lengthB=0;
while (pa != null) {
pa = pa.next;
lengthA++;
}
while (pb != null) {
pb = pb.next;
lengthB++;
}
if (lengthA <= lengthB) {
int n = lengthB - lengthA;
pa = headA; pb = headB;
while (n != 0) {
pb = pb.next;
n--;
}
}else {
int n = lengthA - lengthB;
pa = headA; pb = headB;
while (n!=0) {
pa = pa.next;
n--;
}
}
while (pa != pb) {
pa = pa.next;
pb = pb.next;
}
return pa;
}
}
public class LC75 {
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: