zoukankan      html  css  js  c++  java
  • 合并两个排序的链表

    结点:

    public class ListNode {
        int val;
        ListNode next = null;
    
        ListNode(int val) {
            this.val = val;
        }
    }

    递归方法进行合并:

    public class Solution{
        public ListNode Merge(ListNode list1,ListNode list2){
    
             //检验鲁棒性
             if(list1 == null) return list2; 
             if(list2 == null) return list1; 
    
             //如果list1的第一个元素小,头结点从list1开始;如果list2的第一个元素小,头结点从list2开始
    
             ListNode node = null;
             if(list1.val > list2.val){
                  node = list2;
                  node.next = Merge(list1, list2.next);
             }
             else{
                  node = list1;
                  node.next = Merge(list1.next, list2);
             }
             return node;
        }
    }

    非递归方法进行合并:

    public class Solution{
        public ListNode Merge(ListNode list1,ListNode list2){

             //检验鲁棒性
             if(list1 == null) return list2; 
    if(list2 == null) return list1;

    //如果list1的第一个元素小,头结点从list1开始;如果list2的第一个元素小,头结点从list2开始
    ListNode head
    = null; if(list1.val > list2.val){ head = list2; list2 = list2.next; } else{ head = list1; list1 = list1.next; }
    ListNode node
    = head; while(list1 != null && list2 != null){ if(list1.val > list2.val){ node.next = list2; list2 = list2.next; } else{ node.next = list1; list1 = list1.next; } node = node.next; } if(list1 == null) node.next = list2; if(list2 == null) node.next = list1; return head; } }

    主要思想:

          1) 链表1的头结点值小于链表2的头结点值,则链表1的头结点是合并后链表的头结点;

          2) 在剩余的结点中,链表2的头结点值小于链表1的头结点值,则链表2的头结点是剩余结点的头结点。

          3) 注意代码在鲁棒性方面存在的问题,如空链表时。

  • 相关阅读:
    动态规划最大利润的问题
    【转】mysql基础汇总
    mac使用frida
    Mac 下python3 [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed 解决方法
    mac使用jadx逆向app
    python桶排序代码
    requests_html使用asyncio
    async for的使用
    [转载]微信企业号:企业客户的移动应用入口
    微信服务号、订阅号、企业号差别
  • 原文地址:https://www.cnblogs.com/jiqianqian/p/6603922.html
Copyright © 2011-2022 走看看