LeetCode Intersection of Two Linked Lists

时间:2021-07-16 08:37:54

原题链接在这里:https://leetcode.com/problems/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.

题解:

找到length diff, 长的list head先移动diff次, 再一起移动找相同点.

Time Complexity: O(len1 + len2), len1 is the length of list one. len2 is the length of list two.

Space: O(1).

AC Java:

 /**
* 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) {
int len1 = length(headA);
int len2 = length(headB);
while(len1 > len2){
headA = headA.next;
len1--;
} while(len2 > len1){
headB =headB.next;
len2--;
} while(headA != headB){
headA = headA.next;
headB = headB.next;
} return headA;
} private int length(ListNode head){
int len = 0;
while(head != null){
head = head.next;
len++;
}
return len;
}
}

有一巧妙地方法来综合掉 length diff, a = headA, b = headB, a和b一起移动。当a到了list A的末位就跳到HeadB, b到了List B的末位就跳到HeadA.

等a和b相遇就是first intersection node. 因为a把first intersection node之前的list A部分, list B部分都走了一次. b也是如此. diff就综合掉了.

若是没有intersection, 那么a走到list B的结尾 null时, b正好走到 list A的结尾null, a==b. 返回了null.

Time Complexity: O(len1 + len2), len1 is the length of list one. len2 is the length of list two.

Space: O(1).

AC  Java:

 /**
* 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) {
ListNode a = headA;
ListNode b = headB;
while(a != b){
a = a==null ? headB : a.next;
b = b==null ? headA : b.next;
}
return a;
}
}