zoukankan      html  css  js  c++  java
  • LeetCode 160. Intersection of Two Linked Lists

    分析

    难度 易

    来源

    https://leetcode.com/problems/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.

    解答

     1 package LeetCode;
     2 
     3 public class L160_IntersectionOfTwoLinkedLists {
     4     public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
     5         if(headA==null||headB==null)
     6             return null;
     7         ListNode temp=headA;
     8         while(temp.next!=null)
     9         {
    10             temp=temp.next;
    11         }
    12         temp.next=headB;
    13         ListNode fast=headA;
    14         ListNode slow=headA;
    15         while( fast!=null&&fast.next!=null){
    16             fast=fast.next.next;
    17             slow=slow.next;
    18             if(slow==fast){
    19                 ListNode slow2=headA;
    20                 while(slow2!=slow){
    21                     slow=slow.next;
    22                     slow2=slow2.next;
    23                 }
    24                 temp.next=null;//恢复原链表结构
    25                 return slow2;
    26             }
    27         }
    28         temp.next=null;
    29         return null;
    30     }
    31 }

     

    博客园的编辑器没有CSDN的编辑器高大上啊
  • 相关阅读:
    Hessain 方法重载
    mac 类似Xshell
    idea & datagrip 注册码
    mac 安装mysql 修改密码
    securecrt 的安装
    datagrip的使用
    mac 安装oracle
    mac 安装mysql
    destoon 会员整合Ucenter/Discuz!/PHPWind教程
    destoon 深度整合discuz x2 UC 之免邮箱二次验证
  • 原文地址:https://www.cnblogs.com/flowingfog/p/9941070.html
Copyright © 2011-2022 走看看