LeetCode--Intersection of Two Linked Lists

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

 

posted @ 2015-05-23 18:25  江湖小妞  阅读(195)  评论(0编辑  收藏  举报