【leetcode-合并两个有序链表】

迭代法

java 复制代码
  public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode result = new ListNode(0);
        ListNode cur = result;
        while(list1!=null && list2!=null){ 
            //判断list1和list2的大小
            int val1 =list1.val;
            int val2 =list2.val;
            if(val1<val2){
                //取最小的
                ListNode node = new ListNode(val1);
                cur.next=node;
                cur=cur.next;
                list1=list1.next;
            }else if(val1> val2){
                ListNode node = new ListNode(val2);
                cur.next=node;
                cur=cur.next;
                list2=list2.next;
            }else{
                ListNode node1 = new ListNode(val1);
                ListNode node2 = new ListNode(val2);
                cur.next=node1;
                cur=cur.next;
                cur.next=node2;
                cur=cur.next;
                list1=list1.next;
                list2=list2.next;
            }
        }
        //如果list1还有,则直接将list1插入到后面
        while(list1 !=null){
            cur.next=list1;
            cur=cur.next;
            list1=list1.next;
        }
        //同理list2
        while(list2!=null){
            cur.next=list2;
            cur=cur.next;
            list2=list2.next;
        }
        return result.next;
    }

递归法

java 复制代码
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1 == null || l2 == null){
            return l1==null ? l2 : l1;
        }
        if(l1.val <=l2.val){
            l1.next=mergeTwoLists(l1.next,l2);
            return l1;
        }else{
            l2.next=mergeTwoLists(l1,l2.next);
            return l2;
        }
    }
相关推荐
罗超驿7 小时前
独立实现双向链表_LinkedList
java·数据结构·链表·linkedlist
用头发抵命9 小时前
Vue 3 中优雅地集成 Video.js 播放器:从组件封装到功能定制
开发语言·javascript·ecmascript
蓝冰凌9 小时前
Vue 3 中 defineExpose 的行为【defineExpose暴露ref变量】详解:自动解包、响应性与实际使用
前端·javascript·vue.js
奔跑的呱呱牛9 小时前
generate-route-vue基于文件系统的 Vue Router 动态路由生成工具
前端·javascript·vue.js
柳杉10 小时前
从动漫水面到赛博飞船:这位开发者的Three.js作品太惊艳了
前端·javascript·数据可视化
菜菜小狗的学习笔记10 小时前
剑指Offer算法题(四)链表
数据结构·算法·链表
We་ct10 小时前
LeetCode 148. 排序链表:归并排序详解
前端·数据结构·算法·leetcode·链表·typescript·排序算法
TON_G-T10 小时前
day.js和 Moment.js
开发语言·javascript·ecmascript
Irene199111 小时前
JavaScript 中 this 指向总结和箭头函数的作用域说明(附:call / apply / bind 对比总结)
javascript·this·箭头函数