代码拉取完成,页面将自动刷新
package com.hit.basmath.learn.linked_list;
import com.hit.common.ListNode;
/**
* 160. Intersection of Two Linked Lists
* <p>
* Write a program to find the node at which the intersection of two singly linked lists begins.
* <p>
* For example, the following two linked lists:
* <p>
* A: a1 → a2
* ↘
* c1 → c2 → c3
* ↗
* B: b1 → b2 → b3
* <p>
* begin to intersect at node c1.
* <p>
* Notes:
* <p>
* 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.
*/
public class _160 {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
/**
* Boundary check
*/
if (headA == null || headB == null) return null;
ListNode nodeA = headA;
ListNode nodeB = headB;
/**
* If a & b have different len,
* then we will stop the loop after second iteration
*/
while (nodeA != nodeB) {
/**
* For the end of first iteration,
* we just reset the pointer to the head of another linkedlist
*/
nodeA = (nodeA == null ? headB : nodeA.next);
nodeB = (nodeB == null ? headA : nodeB.next);
}
return nodeA;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。