zoukankan      html  css  js  c++  java
  • 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;
        }
  • 相关阅读:
    linux静态链接库
    查看进程运行时间
    进程间同步-互斥量
    Linux——多线程下解决生产消费者模型
    Linux——线程
    浅谈智能指针的历史包袱
    C++ 模板基础
    用信号量为共享内存添加同步机制
    Linux——浅析信号处理
    浅析fork()和底层实现
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5867346.html
Copyright © 2011-2022 走看看