TGViewer
C# | LeetCode C# | LeetCode @easy_c_sharp_task · 3.17K subscribers
Post #1415 290
Задача: 160. Intersection of Two Linked Lists
Сложность: easy

Даны головы двух односвязных списков headA и headB. Верните узел, в котором эти два списка пересекаются. Если два связанных списка не имеют пересечений, верните null.

Например, следующие два связанных списка начинают пересекаться в узле c1.

Пример:
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
Output: Intersected at '8'
Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory.


👨‍💻 Алгоритм:

1⃣Сохранение ссылок из списка B:
Проходим по всем узлам списка B и сохраняем ссылки (адреса) каждого узла в хеш-таблицу. Это позволит нам быстро проверять, содержится ли узел из списка A в списке B.

2⃣Проверка узлов списка A:
Далее, для каждого узла из списка A проверяем, существует ли такой узел в хеш-таблице, созданной на предыдущем шаге. Если такой узел найден, то он является точкой пересечения, и мы возвращаем этот узел.

3⃣Обработка отсутствия пересечения:
Если до конца списка A не найдено ни одного узла, который бы совпал с узлами из хеш-таблицы, возвращаем null, указывая на отсутствие пересечения между списками.

😎 Решение:
public class Solution {
public ListNode GetIntersectionNode(ListNode headA, ListNode headB) {
HashSet<ListNode> nodesInB = new HashSet<ListNode>();

while (headB != null) {
nodesInB.Add(headB);
headB = headB.next;
}

while (headA != null) {
if (nodesInB.Contains(headA)) {
return headA;
}

headA = headA.next;
}

return null;
}
}


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_c_sharp_task
  1. Oct 16, 2026Задача: 205. Isomorphic Strings Сложность: easy Даны две строки s и t, определите, являютс…
  2. Oct 16, 2026Задача: 1416. Restore The Array Сложность: hard Программа должна была напечатать массив це…
  3. Oct 15, 2026Задача: 217. Contains Duplicate Сложность: easy Дан массив целых чисел nums. Верните true,…
  4. Oct 15, 2026Задача: 759. Employee Free Time Сложность: hard Нам дан список schedule of employees, кото…
  5. Oct 14, 2026Задача: 583. Delete Operation for Two Strings Сложность: medium Даны две строки word1 и wo…
  6. Oct 14, 2026Задача: 1252. Cells with Odd Values in a Matrix Сложность: easy Имеется матрица m x n, кот…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →