码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 160. Intersection of Two Linked Lists

时间:2018-11-11 00:54:26      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:题目   wing   ali   problem   where   The   col   ems   fas   

分析

难度 易

来源

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 }

 

 

LeetCode 160. Intersection of Two Linked Lists

标签:题目   wing   ali   problem   where   The   col   ems   fas   

原文地址:https://www.cnblogs.com/flowingfog/p/9941070.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!