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

leetcode 160. Intersection of Two Linked Lists --------- java

时间:2016-11-20 06:18:25      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:should   turn   follow   java   time   ini   str   function   nal   

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.

 

Notes:

    • If the two linked lists have no intersection at all, return null.
    • The linked lists must retain their original structure after the function returns. 
    • You may assume there are no cycles anywhere in the entire linked structure.
    • Your code should preferably run in O(n) time and use only O(1) memory.

 

直接上代码,比较简单。

 

/**
 * 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 len1 = 1,len2 = 1;
        if( headA == null || headB == null)
            return null;
        ListNode node1 = headA;
        ListNode node2 = headB;
        
        while( node1.next != null ){
            node1 = node1.next;
            len1++;
        }
        while( node2.next != null ){
            node2 = node2.next;
            len2++;
        }
        if( len1 == 0 || len2 == 0 || node1 != node2 )
            return null;
        node1 = headA;
        node2 = headB;
        if( len1 > len2 ){
            while( len1 > len2 ){
                len1--;
                node1 = node1.next;
            }
        }else if( len1 < len2 ){
            while( len1<len2){
                len2--;
                node2 = node2.next;
            }
        }

        while( len1 >0 ){
            if( node1 == node2 )
                return node1;
            node1 = node1.next;
            node2 = node2.next;
            len1--;
        }
        return null;
    }
}

 

leetcode 160. Intersection of Two Linked Lists --------- java

标签:should   turn   follow   java   time   ini   str   function   nal   

原文地址:http://www.cnblogs.com/xiaoba1203/p/6081841.html

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