Q15 Intersection of Two Linked Lists - LeetCode 2nd aprroach

PHOTO EMBED

Tue Jan 17 2023 05:34:30 GMT+0000 (Coordinated Universal Time)

Saved by @Ayush_dabas07

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    
    //TC = same as previous O(m+n)
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode tempa = headA;
        ListNode tempb = headB;

        //using a cycle trick 
        while(tempa != tempb){

            tempa = tempa==null ? headB : tempa.next;
            tempb = tempb==null ? headA : tempb.next;
        }
        return tempa;
    }
}
content_copyCOPY

https://leetcode.com/problems/intersection-of-two-linked-lists/