160. Intersection of Two Linked Lists java

时间:2022-12-09 16:20:19

Write a program to find the node at which the intersection of two singly linked lists begins.

 

For example, the following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

begin to intersect at node c1.

思路:首先得到两者的长度之差,然后长链表减去长度之差,开始比较,如果相同有交集,如果一直到空都不相同,那么就是没有交集。

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA==null||headB==null)//为空返回
	        	return null;
	        	
	        int lengthA=0;
	        int lengthB=0;
	        
	        ListNode a=headA;
	        ListNode b=headB;
	        while(a!=null)//A的长度
	        {
        		lengthA++;
        		a=a.next;
	        }
	        while(b!=null)//B的长度
	        {
	        	lengthB++;
	        	b=b.next;
	        }
	        a=headA;
	        b=headB;
	        
	        int minus=lengthA-lengthB;//长度之差
	        while(minus!=0)//让长链表先走长度之差步
	        {
	            if(minus>0)
	            {
	                a=a.next;
	                minus--;
	            }
	            else
	            {
	                b=b.next;
	                minus++;
	            }
	        }
	        while(a!=null&&b!=null)//以此判断是否相等
        	{
        		if(a==b)//相等则返回
        			return a;
        		else//不相等继续判断
        		{
        			a=a.next;
        			b=b.next;
        		}
        	}
	        return null;//如果没有相等的,那么就返回null
    }
}