160. Intersection of Two Linked Lists

Easy
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.

这道题一开始想的是先reverse两个LinkedList, 但是后来发现返回的时候可能还要reverse回去,这样一来一去不知道多麻烦。然后看了答案的方法,就很简单明确。先让两个LinkedLists从相同长度出发,然后开始同速前进。遇到第一个相同val的节点就返回过来。

/**
 * 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) {
        int lenA = getLen(headA);
        int lenB = getLen(headB);
        int diff = Math.abs(lenA - lenB);
        if (lenA > lenB){
            headA = moveListNSteps(headA, diff);
        } else if (lenB > lenA){
            headB = moveListNSteps(headB, diff);
        }
        while (headA != null && headB != null){
            if (headA.val == headB.val){
                return headA;
            }
            headA = headA.next;
            headB = headB.next;
        }
        return null;
    }
    
    private int getLen(ListNode head){
        int len = 0;
        while (head != null){
            head = head.next;
            len++;
        }
        return len;
    }
    
    private ListNode moveListNSteps(ListNode head, int n){
        int step = 0;
        while (step < n){
            head = head.next;
            step++;
        }
        return head;
    }  
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/f00167ba20fc
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞