160. 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.

 

 

解法1为先算出两个的list的长度,长的先前进长度差,然后一起往后走直到遇到相同的node。

public ListNode MergeKLists(ListNode[] lists) {
        var size = lists.Count();
        if(size==0) return null;
        if(size==1) return lists[0];
        while(size>1)
        {
            int k = (size+1)/2;
            for(int i =0;i<size/2;i++)
            {
                lists[i] = MergeTwoLists(lists[i], lists[i+k]);
            }
            size = k;
        }
        return lists[0];
    }
    
    public ListNode MergeTwoLists(ListNode l1, ListNode l2) {
       if(l1 == null) return l2;
       if(l2 == null) return l1;
       var w1 = l1;
       var w2 = l2;
       var sentinel = new ListNode(-1);
       var dummy = sentinel;
       while(l1 != null && l2 != null)
       {
           if(l1.val >= l2.val) 
           {
               sentinel.next = new ListNode(l2.val);
               sentinel = sentinel.next;
               l2 = l2.next;
           }
           else
           {
               sentinel.next = new ListNode(l1.val);
               sentinel = sentinel.next;
               l1 = l1.next;
           }
       }
       if(l1 == null)
       sentinel.next = l2;
       else
       sentinel.next = l1;
       return dummy.next;
    }

 

另外一种思路是两个list分别续上对方,然后再找。然而这个题的要求是不能改变list的结构,所以我们用判断,如果到tail则转到另外一个list的head。

public ListNode GetIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null || headB == null) return null;
        ListNode a = headA;
        ListNode b = headB;
        while(a!=b)
        {
            a = (a.next == null) ? headB : a.next;
            b=  (b.next == null) ? headA : b.next; 
        }
        return a;
    }

 

posted @ 2016-09-13 09:49  咖啡中不塌缩的方糖  阅读(144)  评论(0编辑  收藏  举报