Pages

Saturday, September 13, 2025

Intersection of Two Linked List (Leetcode-160)

 /**

 * 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) {
        // if either list are null, return null since no intersection
        if(headA == null || headB == null) {
            return null;
        }

        // set up two runners
        ListNode pA = headA;
        ListNode pB = headB;

        while(pA != pB) {
            pA = (pA == null) ? headB : pA.next;
            pB = (pB == null) ? headA : pB.next;
        }
        return pA;
    }
} OUTPUT: All cases are true.

No comments:

Post a Comment

3917. Count Indices With Opposite Parity (Brute Force) O(n2) + Optimized Solution O(n) + tips LEETCODE WEEKLY 500

  class Solution {     public int [] countOppositeParity ( int [] nums ) {          // approach 1 - checks every pair         int n = n...