相交链表
#LeetCode 160题:相交链表,原题链接
原题链接。相交链表–可以打开测试
题目描述
指针法解题
代码演示:可以复制进leetcode 测试
/**
* 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 curA = headA;
ListNode curB = headB;
int a1 = 0;
while(curA != null){
a1++;
curA = curA.next;
}
int a2 = 0;
while(curB != null){
a2++;
curB = curB.next;
}
int a3 = Math.abs(a1 - a2);
//长度长的链表给curA
curA = a1 >= a2 ? headA : headB;
curB = curA == headA ? headB : headA;
while(a3 > 0){
curA = curA.next;
a3--;
}
while(curA != curB){
if(curA.next == null || curB.next == null){
return null;
}
curA = curA.next;
curB = curB.next;
}
return curA;
}
}
单链表-快慢指针法来确定链表中间位置.
一键三连。