|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
- Output: Reference of the node with value = 8
- Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,0,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
复制代码
- /**
- * 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) {
-
- ListNode pa = headA;
- ListNode pb = headB;
-
- int lengthA = 0;
- int lengthB = 0;
-
- while(pa != null){
-
- lengthA ++;
- pa = pa.next;
- }
-
- while(pb != null){
-
- lengthB ++;
- pb = pb.next;
- }
-
- int dif = Math.abs(lengthA - lengthB);
-
- while(dif != 0){
-
- if(lengthA >= lengthB){
-
- headA = headA.next;
- }
- else{
-
- headB = headB.next;
- }
-
- dif--;
- }
-
- while(headA != null && headB != null){
-
- if(headA == headB){
-
- return headA;
- }
-
- headA = headA.next;
- headB = headB.next;
-
- }
-
- return null;
-
- }
- }
复制代码
|
|