160. Intersection of Two Linked Lists

先遍历两个链表,发现较短的那个,之后再把长的list进行去头操作。

得到两个等长的list,之后进行比较,如果有相同的val的node,则记录这个node,之后再向后进行比较。

如果发现有node存在不同,则直接返回null,如果走到尾都没有发现不同的node,则返回当初记录的那个node

JAVA代码:

/**
 * 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) {
        int sizeA=0;
        int sizeB=0;
        ListNode temp=headA;
        while(temp!=null)
        {
            sizeA++;
            temp=temp.next;
        }
        temp=headB;
        while(temp!=null)
        {
            sizeB++;
            temp=temp.next;
        }
        
        
        ListNode longList=null;
        ListNode shortList=null;
        int longSize=0;
        int shortSize=0;
        
        if(sizeA>sizeB)
        {
            longList=headA;
            shortList=headB;
            longSize=sizeA;
            shortSize=sizeB;
        }
        else
        {
            longList=headB;
            shortList=headA;
            longSize=sizeB;
            shortSize=sizeA;
        }
        temp=null;
        
        int cha=longSize-shortSize;
        
        for(int i=0;i<cha;i++)
            longList=longList.next;
        
        for(int i=0;i<shortSize;i++)
        {
            if(longList.val==shortList.val)
            {
                if(temp==null)
                    temp=longList;
            }
            else
            {
                if(temp!=null)
                {
                    temp=null;
                    break;
                }
            }
            
            longList=longList.next;
            shortList=shortList.next;
        }
        
        return temp;
    }
}
原文地址:https://www.cnblogs.com/aguai1992/p/5346311.html