160. Intersection of Two Linked Lists

Tricky one

time: O(m+n)

space: O(1)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    /*
        41845661 845
        56184541 845
    */
    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 b;
    }
}

把兩個linked 拼起來一起走的話

same logical

len solution

long len list, cut head,

then compare each other, not equal keep move

final return current head (equal!!)

time: O(n)

space: O(1)

Last updated

Was this helpful?