1. 对应力扣题目连接
2. 实现思路
- 链表详情:
考虑使用双指针:
解法一:
- 具体代码,详见3. 实现案例代码
- 解析:
思路:因为链表按照如图的箭头走向,走的总路程是相等的,一定会相交于c点- 如图:
- 如图:因为总的里程数相等一定会相交于c点,即:得到相交的节点8,作为头节点返回即可。
- 如图:
解法二:
- 因为存在相交节点,所有相交节点位置一定是在短节点内,可以先移动长节点到和短节点相同长度的位置再进行遍历判断,节点是否相同即可。
- 如图:
2. 实现案例代码
public class IntersectionOfLinkedLists {
public static void main(String[] args) {
// 示例链表:[4, 1, 8, 4, 5]
ListNode headA = new ListNode(4);
headA.next = new ListNode(1);
ListNode intersectNode = new ListNode(8);
headA.next.next = intersectNode;
intersectNode.next = new ListNode(4);
intersectNode.next.next = new ListNode(5);
// 示例链表:[5, 0, 1, 8, 4, 5]
ListNode headB = new ListNode(5);
headB.next = new ListNode(0);
headB.next.next = new ListNode(1);
headB.next.next.next = intersectNode;
// 找到相交节点
ListNode result = getIntersectionNode(headA, headB);
if (result != null) {
System.out.println("Intersected at '" + result.val + "'");
} else {
System.out.println("No intersection");
}
}
/**
* 解法一:
* @param headA
* @param headB
* @return
*/
public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
ListNode pA = headA;
ListNode pB = headB;
// 继续循环,直到两个指针相遇
while (pA != pB) {
// 如果 pA 到达末尾,将其重定位到 headB
pA = (pA == null) ? headB : pA.next;
// 如果 pB 到达末尾,将其重定位到 headA
pB = (pB == null) ? headA : pB.next;
}
// 当 pA == pB 时,要么是相交节点,要么是 null
return pA;
}
/**
* 解法二:
* @param headA
* @param headB
* @return
*/
public static ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
ListNode curA = headA;
ListNode curB = headB;
int lenA = 0, lenB = 0;
while (curA != null) { // 求链表A的长度
lenA++;
curA = curA.next;
}
while (curB != null) { // 求链表B的长度
lenB++;
curB = curB.next;
}
curA = headA;
curB = headB;
// 让curA为最长链表的头,lenA为其长度
// 即:如果B链表长度 > A链表长度,则交换(curA, curB)
if (lenB > lenA) {
//1. swap (lenA, lenB);
int tmpLen = lenA;
lenA = lenB;
lenB = tmpLen;
//2. swap (curA, curB);
ListNode tmpNode = curA;
curA = curB;
curB = tmpNode;
}
// 求长度差
int gap = lenA - lenB;
// 让curA和curB在同一起点上(末尾位置对齐)
while (gap-- > 0) {
curA = curA.next;
}
// 遍历curA 和 curB,遇到相同则直接返回
while (curA != null) {
if (curA == curB) {
return curA;
}
curA = curA.next;
curB = curB.next;
}
return null;
}
}