flowingfog

偶尔刷题

  博客园  :: 首页  :: 新随笔  :: 联系 ::  :: 管理

分析

难度 易

来源

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 }

 

 

posted on 2018-11-10 23:30  flowingfog  阅读(60)  评论(0编辑  收藏