力扣160题目
建议大家刷题前先写个大概思路,边界问题、细节问题就都迎刃而解了
代码如下:
//使用两个for循环
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null){
return null;
}
ListNode curA = headA;
ListNode curB;
while (curA != null){
curB = headB;
while (curB != null){
if(curA == curB){
return curA;
}else {
curB = curB.next;
}
}
curA = curA.next;
}
return null;
}
//思路2(思路见笔记)
public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
int lenA = 0;
int lenB = 0;
ListNode curA = headA;
ListNode curB = headB;
while (curA != null){
lenA++;
curA = curA.next;
}
while (curB != null){
lenB++;
curB = curB.next;
}
curA = headA;
curB = headB;
for (int i = 1; i <= Math.abs(lenA - lenB); i++){
if(lenA >= lenB){
curA = curA.next;
}else {
curB = curB.next;
}
}
while (curA != null){
if(curA == curB){
return curA;
}else {
curA = curA.next;
curB = curB.next;
}
}
return null;
}