LeetCode刷题实战160:相交链表
共 2122字,需浏览 5分钟
·
2021-01-20 14:00
Write a program to find the node at which the intersection of two singly linked lists begins.
题意
解题
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
//1.
if(headA==null||headB==null){
return null;
}
//2.
ListNode pa=headA;
ListNode pb=headB;
boolean isPaChange=false;
boolean isPbChange=false;
//3.
while(pa!=null&&pb!=null){
//4.
if(pa==pb){
return pa;
}
//5.
pa=pa.next;
pb=pb.next;
//6.
if(isPaChange&&isPbChange&&pa==null&&pb==null){
break;
}
//7.
if(pa==null){
pa=headB;
isPaChange=true;
}
if(pb==null){
pb=headA;
isPbChange=true;
}
}
//8.
return null;
}
}