简单题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;
    }
}
相关推荐
乌萨奇也要立志学C++几秒前
二叉树OJ题(单值树、相同树、找子树、构建和遍历)
数据结构·算法
知其然亦知其所以然21 分钟前
JVM社招面试题:队列和栈是什么?有什么区别?我在面试现场讲了个故事…
java·后端·面试
harmful_sheep29 分钟前
Spring 为何需要三级缓存解决循环依赖,而不是二级缓存
java·spring·缓存
星辰大海的精灵30 分钟前
如何确保全球数据管道中的跨时区数据完整性和一致性
java·后端·架构
大大。33 分钟前
van-tabbar-item选中active数据变了,图标没变
java·服务器·前端
nc_kai36 分钟前
Flutter 之 每日翻译 PreferredSizeWidget
java·前端·flutter
Codebee1 小时前
OneCode:AI时代的先锋——注解驱动技术引领开发范式变革
java
勤奋的知更鸟1 小时前
Java 编程之状态模式
java·开发语言·状态模式
架构个驾驾1 小时前
深入浅出MyBatis-Plus实战指南
java
SimonKing1 小时前
解锁万能文件内容分析工具:Apache Tika
java·后端·程序员