分析
难度 易
来源
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:
null
.解答
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
原文:https://www.cnblogs.com/flowingfog/p/9941070.html