Sponsored
Sponsored
First, traverse both linked lists to determine their lengths. Calculate the difference in lengths and advance the pointer of the longer list by the length difference. Then move both pointers in tandem to find the intersection node.
Time Complexity: O(m + n).
Space Complexity: O(1).
1public class Solution {
2 public class ListNode {
3 public int val;
4 public ListNode next;
5 public ListNode(int x) { val = x; next = null; }
6 }
7
8 private int GetLength(ListNode head) {
9 int length = 0;
10 while (head != null) {
11 length++;
12 head = head.next;
13 }
14 return length;
15 }
16
17 public ListNode GetIntersectionNode(ListNode headA, ListNode headB) {
18 int lenA = GetLength(headA);
19 int lenB = GetLength(headB);
20
21 if (lenA > lenB) {
22 for (int i = 0; i < lenA - lenB; i++) headA = headA.next;
23 } else {
24 for (int i = 0; i < lenB - lenA; i++) headB = headB.next;
25 }
26
27 while (headA != headB) {
28 headA = headA.next;
29 headB = headB.next;
30 }
31 return headA;
32 }
33}The C# solution makes use of an auxiliary function to calculate the lengths of the linked lists, adjusts one of the heads if needed, and searches for the intersection node.
Use two pointers, each starting at the head of one list. Traverse the list until a pointer reaches null, then start traversing the other list from the beginning. Repeat until the two pointers meet at the intersection node.
Time Complexity: O(m + n).
Space Complexity: O(1).
1public class Solution {
public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) { val = x; next = null; }
}
public ListNode GetIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) return null;
ListNode a = headA;
ListNode b = headB;
while (a != b) {
a = (a == null) ? headB : a.next;
b = (b == null) ? headA : b.next;
}
return a;
}
}The C# solution uses two pointers, initialized at the heads of the lists. They switch to the other list's head at the end of the current list traversal and continue until they meet at the intersection node or return null.