相交链表的相交节点
作者:互联网
给你两个单链表的头节点headA
和headB
,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回null
。
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
输出:Intersected at '8'
/**
* 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 pA = headA, pB = headB;
while (pA != pB) {
if(pA == null){
pA = headB;
}else{
pA = pA.next;
}
if(pB == null){
pB = headA;
}else{
pB = pB.next;
}
}
return pA;
}
}
标签:pB,ListNode,相交,链表,pA,headB,headA,null,节点 来源: https://blog.csdn.net/voilde/article/details/122377256