【算法1】-【2个链表是否相交】
确定相交,则返回相交的节点;否则返回null;(算法均能做到O(n))
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
ListNode pt1 = headA;
ListNode pt2 = headB;
int circleCount = 0;
while (pt1 != pt2) {
if (pt1 == null) {
circleCount++;
}
if (circleCount >= 2) {
break;
}
pt1 = pt1 == null ? headB : pt1.next;
pt2 = pt2 == null ? headA : pt2.next;
}
return pt1;
}
}
CVTE公司福利 707人发布