• 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.
    复制代码

    链接:  http://leetcode.com/problems/intersection-of-two-linked-lists/

    2/19/2017, Java

    一开始的思路是,借用判断cycled linked list来。先从nodeA出发遍历,把最后一个node的next设为nodeB的head,这样第二次遍历时候通过slow, fast来找进入圈里的第一个node。

    看起来很巧妙,但是是错误的,因为无法确定当fast, slow相遇时,是否是在进入圈里的第一个node,其实,可能为任一node。

    正确解法,借鉴别人:

    判断2个list的长度差,从距末尾相同长度开始(此时至少一个list是在head),一个个比较。

    注意第一步之后要将a, b重新设到合理的位置,尤其是diff == 0时

     1 public class Solution {
     2     public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
     3         if (headA == null || headB == null) return null;
     4         int diff = 0;
     5         ListNode a = new ListNode(0);
     6         ListNode b = new ListNode(0);
     7         a = headA;
     8         b = headB;
     9         
    10         while(a != null && b != null) {
    11             a = a.next;
    12             b = b.next;
    13         }
    14         while (a != null) {
    15             diff++;
    16             a = a.next;
    17         }
    18         while (b != null) {
    19             diff--;
    20             b = b.next;
    21         }
    22         if (diff > 0) {
    23             a = headA;
    24             while (diff > 0) {
    25                 a = a.next;
    26                 diff--;
    27             }
    28             b = headB;
    29         } else if (diff < 0) {
    30             b = headB;
    31             while (diff < 0) {
    32                 b = b.next;
    33                 diff++;
    34             }
    35             a = headA;
    36         } else {
    37             a = headA;
    38             b = headB;
    39         }
    40         
    41         while (a != null && b != null) {
    42             if (a == b) return a;
    43             a = a.next;
    44             b = b.next;
    45         }
    46         return null;
    47     }
    48 }
  • 相关阅读:
    Http Get与Post的区别
    华为USG6000V防火墙简单配置案例
    华为USG6000V防火墙简单配置案例
    基于三层交换机的VRRP技术--MSTP、VRRP的综合运用
    ci test
    CI框架 default_controller 如何设置为:'目录/Controller' 转
    查看django版本的方法
    Django如何安装指定版本
    django学习--2 模板
    django学习--1
  • 原文地址:https://www.cnblogs.com/panini/p/6418745.html
Copyright © 2020-2023  润新知