此题为力扣链表题目:
📌 文章目录:
题目:
1️⃣.题目解析
题目要求:两个相交的链表,找到两个链表相交的第一个公共交点,这道题需要定义两个结点类型变量,一个用于指向较长链表(pl),一个用于指向较短链表(ps),较长的 pl 先走两个链表长度的差值步,两个指针再同时走,直到相遇,返回相遇的那个结点
2️⃣.代码实现
步骤一、先判断两个链表是不是为空,如果有一个为空,链表无法相交,直接返回空对象
if (headA == null || headB == null){
return null;
}
步骤二、定义两个结点类型变量,pl 指向较长链表,ps 指向较短链表,这里先默认 A链表长
ListNode pl = headA;
ListNode ps = headB;
步骤三、计算两个链表长度,pl 和 ps 走完后要重新赋值
int lenA = 0;
int lenB = 0;
while(pl != null){
lenA++;
pl = pl.next;
}
pl = headA;
while(ps != null){
lenB++;
ps = ps.next;
}
ps = headB;
步骤四、计算两个链表长度的差值,判断保证差值大于 0,如果差值小于 0 ,证明 B 更长,交换 pl 和ps 的指向
int len = lenA - lenB;
if (len < 0){
pl = headB;
ps = headA;
len = lenB - lenA;
}
步骤五、指向长链表的 pl 多走差值步
while(len != 0){
len--;
pl = pl.next;
}
步骤六、pl 和 ps 同时走,直到相遇
while(pl != ps){
ps = ps.next;
pl = pl.next;
}
步骤七、判断两个链表有没有哪个走到了空,走到空,证明两个链表平行没有交点,题目中的这种情况
if (pl == null || ps == null){
return null;
}
步骤八、返回交点即可
return pl;
3️⃣.全部代码
/**
* 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 pl = headA;
ListNode ps = headB;
int lenA = 0;
int lenB = 0;
while(pl != null){
lenA++;
pl = pl.next;
}
pl = headA;
while(ps != null){
lenB++;
ps = ps.next;
}
ps = headB;
int len = lenA - lenB;
if (len < 0){
pl = headB;
ps = headA;
len = lenB - lenA;
}
while(len != 0){
len--;
pl = pl.next;
}
while(pl != ps){
ps = ps.next;
pl = pl.next;
}
if (pl == null || ps == null){
return null;
}
return pl;
}
}