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

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode p1 = headA;
        ListNode p2 = headB;
        
        while (p1 != p2) { // when out, p1 = p2, if cant find intersection, it will be null
            if (p1 == null) {
                p1 = headB;
            } else {
                p1 = p1.next;
            }
            
            if (p2 == null) {
                p2 = headA;
            } else {
                p2 = p2.next;
            }
        }
        return p1;
    }
}

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)

/**
 * 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 lenA = getLen(headA);
        int lenB = getLen(headB);
        while (lenA > lenB) {
            headA = headA.next;
            lenA--;
        } 
        while (lenB > lenA) {
            headB = headB.next;
            lenB--;
        }   
        while (headA != headB) {
            headA = headA.next;
            headB = headB.next;
        }
        return headA;
    }
    private int getLen(ListNode node) {
        int len = 1;
        while (node != null) {
            node = node.next;
            len++;
        }
        return len;
    }
}

Last updated