码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode--Intersection of Two Linked Lists

时间:2015-05-23 19:54:09      阅读:129      评论: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.

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.

问题描述:找出两个链表相交的地方。注意:如果两个链表一直都链表尾都没有相交的地方则返回null;不能破坏链表的原结构;可以假设原链表中没有环;时间和空间复杂度分别为:O(n),O(1).

问题分析:可以分别计算两个链表的长度,比较长度相等的那部分即可。返回第一个相等的元素。(比较两个节点是否相等,只需比较节点的val是否相等即可,因为输入的是值列表,并非真正的指向同一块内存空间的节点链表)

代码如下:

/**
 * 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) {
            ListNode l1 = headA;
        ListNode l2 = headB;
        int le1=0, le2=0;
        if(headA==null || headB==null)
            return null;
        
        while(l1.next!=null){
            l1 = l1.next;
            le1++;
        }
        while(l2.next!=null){
            l2 = l2.next;
            le2++;
        }
        if(l1.val!=l2.val){ //如果最后尾节点的值不相等,则一定不相交
            return null;
        }
                   
        if(le2==le1){
            l1 = headA;
            l2 = headB;
            while(l1!=null && l2!=null){
                if(l1.val==l2.val)
                    return l1;
                l1 = l1.next; 
                l2 = l2.next;
            }
        }
        
        if(le1>le2){
            l1 = headA;
            l2 = headB;
            int le = le1-le2;
            for(int i=0; i<le; i++)
                l1 = l1.next;
            while(l1!=null && l2!=null){
                if(l1.val==l2.val)
                    return l1;
                l1 = l1.next; 
                l2 = l2.next;
            }
        }
        
        if(le1<le2){
            l1 = headA;
            l2 = headB;
            int le = le2-le1;
            for(int i=0; i<le; i++)
                l2 = l2.next;
            while(l1!=null && l2!=null){
                if(l1.val==l2.val)
                    return l1;
                l1 = l1.next; 
                l2 = l2.next;
            }
        }
        
        return null;
    }
}

 

LeetCode--Intersection of Two Linked Lists

标签:

原文地址:http://www.cnblogs.com/little-YTMM/p/4524700.html

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