LeetCode 160. Intersection of Two Linked Lists
Posted flowingfog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }
以上是关于LeetCode 160. Intersection of Two Linked Lists的主要内容,如果未能解决你的问题,请参考以下文章
[JavaScript 刷题] 链表 - 相交链表, leetcode 160