LeetCode – 160. Intersection of Two Linked Lists

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3  

begin to intersect at node c1.

Notes:

  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory.

This problem is actually quite simple. If two linked lists intersect, then iterate through both lists simultaneously, swap them after completion, and eventually reach the intersection point. For example, the intersection point is the last 3 items. A has 6 items (3+3), and B has 7 items (4+3). When A finishes, B is the second to last. Then, when A reaches the fourth item B, B has reached the third item A. The next item is the intersection point.

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; ListNode currB = headB; while(currA != currB){ if(currA ==null){ currA = headB; } else{ currA = currA.next; } if(currB == null){ currB = headA; } else{ currB = currB.next; } } return currA; } }

This siteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)Please retain the following annotations when sharing or adapting:

Original author:Jake Tao,source:"LeetCode – 160. Intersection of Two Linked Lists"

200
0 0 200

Further Reading

Post a reply

Log inYou can only comment after that.
Share this page
Back to top