《LeetCode力扣练习》代码随想录——链表(链表相交—Java)
刷题思路来源于 代码随想录
面试题 02.07. 链表相交
-
/*** 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;}int lenA=0;int lenB=0;ListNode tempA=headA;ListNode tempB=headB;while(tempA!=null){lenA++;tempA=tempA.next;}while(tempB!=null){lenB++;tempB=tempB.next;}int different=lenA>lenB?(lenA-lenB):(lenB-lenA);tempA=headA;tempB=headB;while(different>0){if(lenA>lenB){tempA=tempA.next;}else{tempB=tempB.next;}different--;}int count =lenA<lenB?lenA:lenB;while(count>0){if(tempA==tempB){return tempA;}else{tempA=tempA.next;tempB=tempB.next;}count--;}return null;} }