链表相交
问题描述
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
解题思路
- 遍历链表A,B,确定链表A,B长度。
- 令指向更长链表的指针为快指针,另一个为慢指针
- 快指针先行n步(n为链表A,B的长度之差)
- 同时移动快慢指针若两个指针指向了相同结点则返回该结点否则返回空指针
代码实现
/**
* 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) {
int lenA = 0;
int lenB = 0;
ListNode curA = headA;
ListNode curB = headB;
//遍历链表,确定链表长度
while (curA != null) {
curA = curA.next;
lenA++;
}
while (curB != null) {
curB = curB.next;
lenB++;
}
//注意:此时curA与curB都指向了链表末,下一步操作前要使其指向链表头
curA = headA;
curB = headB;
//令curA指向更长的链表并相应改变或不改变lenA
if (lenB > lenA) {
int tmp = lenA;
lenA = lenB;
lenB = tmp;
ListNode temp = curA;
curA = curB;
curB = temp;
}
int n = lenA - lenB;
//curA为快指针比curB先行n步
while (n > 0) {
curA = curA.next;
n--;
}
//同时移动快慢指针若两个指针指向了相同结点则返回该结点否则返回空指针
while (curA != null) {
if (curA == curB) {
return curA;
}
curA = curA.next;
curB = curB.next;
}
return null;
}
}