Home [Easy] Intersection of Two Linked Lists
Post
Cancel

[Easy] Intersection of Two Linked Lists

‘Intersection of Two Linked Lists’ in LeetCode (Easy)


📌 Problem

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

📌 Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
 * 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 p1 = headA, p2 = headB;
        int len1 = 0, len2 = 0;
        
        while (p1 != null) {
            p1 = p1.next;
            len1++;
        }
        while (p2 != null) {
            p2 = p2.next;
            len2++;
        }

        p1 = headA;
        p2 = headB;

        if (len1 > len2) {
            for (int i = 0; i < len1 - len2; i++) {
                p1 = p1.next;
            }
        } else {
            for (int i = 0; i < len2 - len1; i++) {
                p2 = p2.next;
            }
        }

        while (p1 != p2) {
            // System.out.println("p1 : " + p1.val);
            // System.out.println("p2 : " + p2.val);
            // System.out.println();
            
            p1 = p1.next;
            p2 = p2.next;
        }
        return p1;
    }
}
This post is licensed under CC BY 4.0 by the author.

[Easy] Remove Linked List Elements

[Easy] Remove Duplicates from Sorted List

Comments powered by Disqus.