169.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.
开始在节点c1处相交。
Notes:
- If the two linked lists have no intersection at all, return
null
.如果两个链接列表根本没有交集,则返回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.您的代码最好在O(n)时间内运行,并且只使用O(1)内存。
解答:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public ListNode getIntersectionNode(ListNode headA, ListNode headB) { 14 if(headA==null || headB==null) return null; 15 ListNode a=headA,b=headB; 16 while(a!=b){ 17 a=(a!=null) ? a.next:headB; 18 b=(b!=null) ? b.next:headA; 19 } 20 return a; 21 } 22 }
详解:
分别用两个指针指向两个链表的开头,当其中一条遍历到末尾时,跳到另一条链表继续遍历,两个指针最终会相等。
要么在交点处相遇,要么在各自末尾空节点处。如果没有交点,两个指针走过的路径长度都是两个链表长度之和;如果有交点,交点后的长度相等,总长度也相等,所以交点前的长度也相等。