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.

这道题其实很简单,如果两个相交,那么两个linkedlist同时遍历,完成后交换遍历,最终会到交汇点。例如交汇是最后3个,A是6个(3+3),B是7个(4+3),那个A结束的时候B在倒数第二个,接着A遍历到第四个B的时候,B遍历也正好到了A的第三个,下一个数就是交汇点。

/**
 * 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) {
        
        if(headA == null || headB == null) return null;
        ListNode currA = headA;
        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 site uses Akismet to reduce spam. Learn how your comment data is processed.