zoukankan      html  css  js  c++  java
  • [LeetCode]160.Intersection of Two Linked Lists(2个链表的公共节点)

    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.

    可以将A,B两个链表看做两部分,交叉前与交叉后。例子中

    交叉前A:          a1 → a2

    交叉前B:   b1 → b2 → b3

    交叉后AB一样: c1 → c2 → c3

    所以 ,交叉后的长度是一样,所以,交叉前的长度差即为总长度差。

    只要去除长度差,距离交叉点就等距了。

     1 public class Solution {
     2     public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
     3         int lenA=0 ,lenB=0;
     4         int dis;
     5         for(ListNode x = headA;x != null;x = x.next) lenA++; //len of a
     6         for(ListNode x = headB;x != null;x = x.next) lenB++;// len of b
     7         dis = lenB - lenA;//distence of a and b
     8     
     9         if(dis > 0)//b is longer than a  move headb 
    10             for(int i = dis;i > 0;i --) headB = headB.next;
    11         else  // a is longer than b move heada
    12             for(int i = -dis;i > 0;i --) headA = headA.next;
    13         
    14         while(headA != headB){ // heada and headb are equal?
    15             headA = headA.next;
    16             headB = headB.next;
    17         }
    18         return headA;
    19     }

    参考:

    http://www.cnblogs.com/ganganloveu/p/4128905.html

  • 相关阅读:
    苹果一体机发射Wi-Fi
    iphone 屏蔽系统自动更新,消除设置上的小红点
    data parameter is nil 异常处理
    copy与mutableCopy的区别总结
    java axis2 webservice
    mysql 远程 ip访问
    mysql 存储过程小问题
    mysql游标错误
    is not writable or has an invalid setter method错误的解决
    Struts2中关于"There is no Action mapped for namespace / and action name"的总结
  • 原文地址:https://www.cnblogs.com/zle1992/p/6804922.html
Copyright © 2011-2022 走看看