zoukankan      html  css  js  c++  java
  • 160. Intersection of Two Linked Lists java

    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
        }
    }
    

      

  • 相关阅读:
    bzoj3786 星系探索
    [JSOI2008]火星人
    [NOI2005]维护数列
    [POI2008]砖块Klo
    郁闷的出纳员
    [HNOI2002]营业额统计
    [BZOJ1651][Usaco2006 Feb]Stall Reservations 专用牛棚
    [BZOJ2124]等差子序列
    [BZOJ3038]上帝造题的七分钟2
    [BZOJ1711][Usaco2007 Open]Dining吃饭
  • 原文地址:https://www.cnblogs.com/zhangfanxmian/p/6872437.html
Copyright © 2011-2022 走看看