简单题21 - 合并两个有序链表(Java)20240917

问题描述:
java代码:
java 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode res = new ListNode(0);
        ListNode cur = res;
        while(list1 != null || list2 != null){
            if(list1 != null && list2 != null){
                if (list1.val == list2.val){
                    cur.next = new ListNode(list1.val);
                    cur = cur.next;
                    cur.next = new ListNode(list2.val);
                    list1 = list1.next;
                    list2 = list2.next;
                }else{
                    if(list1.val>list2.val){
                        cur.next = new ListNode(list2.val);
                        list2 = list2.next;
                    }else{
                        cur.next = new ListNode(list1.val);
                        list1 = list1.next;
                    }
                }
            }else if(list1 != null){
                cur.next = new ListNode(list1.val);
                list1 = list1.next;
            }else if(list2 != null){
                cur.next = new ListNode(list2.val);
                list2 = list2.next;
            }
            cur = cur.next;
        }
        return res.next;
    }
}
相关推荐
JavaArchJourney12 分钟前
HashMap 源码分析
java
hrrrrb43 分钟前
【Java Web 快速入门】十、AOP
java·前端·spring boot
xnglan44 分钟前
蓝桥杯手算题和杂题简易做法
数据结构·数据库·c++·python·算法·职场和发展·蓝桥杯
凛冬君主1 小时前
插入排序专栏
java·算法·排序算法
檀越剑指大厂1 小时前
【开发语言】Groovy语言:Java生态中的动态力量
java·开发语言
Tina学编程2 小时前
线程P5 | 单例模式[线程安全版]~懒汉 + 饿汉
java·单例模式·线程安全
我们从未走散2 小时前
设计模式学习笔记-----单例模式
java·笔记·学习·单例模式·设计模式
期待のcode2 小时前
Maven
java·spring·maven·mybatis
IT毕设实战小研2 小时前
Java毕业设计选题推荐 |基于SpringBoot的健身爱好线上互动与打卡社交平台系统 互动打卡小程序系统
java·开发语言·vue.js·spring boot·vue·毕业设计·课程设计
long3164 小时前
java 工厂方法设计模式 FactoryMethod
java·开发语言·后端·设计模式