image.png

Simulation

Solution 1 HashSet

By adding all the node in List 1 in to a HashSet, and traverse the List 2 to find it first node that equals.

Solution 2 List Traverse

Find the length difference of two list. Let the longer list run the difference first.
Leetcode 160 Intersection of Two Linked Lists - 图2

Solution 3 List Traverse Optimized

  1. Scan both lists
  2. For each list once it reaches the end, continue scanning the other list
  3. Once the two runner equal to each other, return the position

Leetcode 160 Intersection of Two Linked Lists - 图3

Implementation

Solution 1

  1. public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
  2. Set < ListNode > set = new HashSet < ListNode > ();
  3. while (headA != null) {
  4. set.add(headA);
  5. headA = headA.next;
  6. }
  7. while (headB != null) {
  8. if (set.contains(headB)) {
  9. return headB;
  10. }
  11. headB = headB.next;
  12. }
  13. return null;
  14. }

Solution 2

Solution 3

  1. public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
  2. ListNode tempHeadA = headA;
  3. ListNode tempHeadB = headB;
  4. while (!(headA == null && headB == null)) {
  5. if (headA == headB) {
  6. return headA;
  7. }
  8. if (headB == null) {
  9. headB = tempHeadA;
  10. } else if (headA == null) {
  11. headA = tempHeadB;
  12. } else {
  13. headA = headA.next;
  14. headB = headB.next;
  15. }
  16. }
  17. return null;
  18. }
  1. public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
  2. if (headA==null || headB == null)
  3. return null;
  4. ListNode tempA = headA, tempB = headB;
  5. while(tempA!=tempB){
  6. tempA = tempA==null ?headB:tempA.next;
  7. tempB = tempB==null ?headA:tempB.next;
  8. }
  9. return tempA;
  10. }