码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 160 Intersection of Two Linked Lists

时间:2015-06-05 19:28:52      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

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.

解题思路:

先遍历两个list的长度,然后长的减去短的,之后同时遍历即可,JAVA实现如下:

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA==null||headB==null)
        	return null;
        int lengthA=0,lengthB=0;
        ListNode tempA=headA,tempB=headB;
    	while(tempA!=null){
    		tempA=tempA.next;
    		lengthA++;
        }
    	while(tempB!=null){
    		tempB=tempB.next;
    		lengthB++;
        }
    	if(lengthB>lengthA){
    		tempA=headA;
    		headA=headB;
    		headB=tempA;
    		int temp=lengthA;
    		lengthA=lengthB;
    		lengthB=temp;
    	}
    	int length=lengthA-lengthB;
    	while(length-->0)
    		headA=headA.next;
    	while(headA!=null){
    		if(headA==headB)
    			return headA;
    		headA=headA.next;
    		headB=headB.next;
    	}
    	return headA; 
    }

 

Java for LeetCode 160 Intersection of Two Linked Lists

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4555154.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!