您的位置 首页 JAVA(2017)

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;
    }
}
看完了?留个评分呗?
[0人评了分,平均: 0/5]

本站原创文章皆遵循“署名-非商业性使用-相同方式共享 3.0 (CC BY-NC-SA 3.0)”。转载请保留以下标注:

原文来源:《LeetCode – 160. Intersection of Two Linked Lists》

发表评论

邮箱地址不会被公开。

返回顶部