zoukankan      html  css  js  c++  java
  • merge two sorted lists

    Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

    Example:

    Input: 1->2->4, 1->3->4
    Output: 1->1->2->3->4->4

    合并两个已经排好序的链表,就跟合并两个排好序的数组一样,可以使用归并排序的思想。

    第一种就是使用归并排序思想,不使用递归

      /*
        非递归,利用归并思想,合并时使用额外链表
        */
        /*
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            
            ListNode first=new ListNode(-1);  //用于返回的链表
            ListNode node=first;  //用于在first链表上移动
            
           
            if(l1==null) return l2;
            if(l2==null) return l1;
            
            while(l1!=null&&l2!=null){
                if(l1.val>l2.val){
               node.next=l2; node=node.next; //这里不要忘记,不然只是在一个节点操作 l2=l2.next; }else{ node.next=l1; node=node.next; l1=l1.next; } } //这里需要,因为是在额外链表中操作的。
        while(l1!=null){ node.next=l1; node=node.next; l1=l1.next; } while(l2!=null){ node.next=l2; node=node.next; l2=l2.next; } return first.next; }

    归并,合并时不使用额外链表:

    public ListNode merge(ListNode head1, ListNode head2)  
    {  
        ListNode helper = new ListNode(0);  
        helper.next = head1;  //用l1作为结果集
        ListNode pre = helper;  
        while(head1!=null && head2!=null)  
        {  
            if(head1.val<head2.val)  
            {  
                head1 = head1.next;  
            }  
            else  //将小的元素插入到l1中
            {  
                ListNode next = head2.next;  
                head2.next = pre.next;  
                pre.next = head2;  
                head2 = next;  
            }  
            pre = pre.next;  
        }  
        while(head2!=null)  
        {  
            pre.next = head2;  
        }  
        return helper.next;  
    }  

    第二种方法,递归

     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
             if(l1==null) return l2;
            if(l2==null) return l1;
             
             ListNode mergeNode;
             if(l1.val<l2.val){
                 mergeNode=l1;
                 mergeNode.next=mergeTwoLists(l1.next,l2);
             }else{
                  mergeNode=l2;
                 mergeNode.next=mergeTwoLists(l2.next,l1);
             }
             return mergeNode;
         }
    
    
  • 相关阅读:
    [BZOJ4199][NOI2015]品酒大会
    [BZOJ4198][Noi2015]荷马史诗
    [BZOJ4197][Noi2015]寿司晚宴
    [BZOJ4196][NOI2015]软件包管理器
    2016-11-15NOIP模拟赛
    2016.6.30模拟赛
    BZOJ3672: [Noi2014]购票
    UOJ#191. 【集训队互测2016】Unknown
    第四届CCF软件能力认证(CSP2015) 第五题(最小花费)题解
    bzoj3926: [Zjoi2015]诸神眷顾的幻想乡 对[广义后缀自动机]的一些理解
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8059373.html
Copyright © 2011-2022 走看看