Seawolf 发表于 2019-8-4 23:26:08

LeetCode160. 相交链表



Input: intersectVal = 8, listA = , listB = , 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 . From the head of B, it reads as . 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;
      
    }
}

页: [1]
查看完整版本: LeetCode160. 相交链表