day36(12.17)——leetcode面试经典150

21. 合并两个有序链表

21. 合并两个有序链表

我的微服务还没正式开启呢,我这两天在做一个贼简单的网站,昨天写的很兴奋,写到三点,整的今天巨困!!!

题目:

题解:

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 cur = new ListNode(0);
        ListNode list = cur;
        while(list1!=null && list2!=null) {
            if(list1.val<list2.val) {
                cur.next = new ListNode(list1.val);
                list1 = list1.next; 
            }
            else {
                cur.next = new ListNode(list2.val);
                list2 = list2.next;
            }
            cur = cur.next;
        }
        while(list1 != null) {
            cur.next = new ListNode(list1.val);
            list1 = list1.next;
            cur = cur.next;
        }
        while(list2 != null) {
            cur.next = new ListNode(list2.val);
            list2 = list2.next;
            cur = cur.next;
        }
        return list.next;
    }
}

还有另一种写法,思路差不多

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 cur = new ListNode(0);
        ListNode list = cur;
        while(list1!=null || list2!=null) {
            if(list1 == null && list2 != null) {
                cur.next = new ListNode(list2.val);
                list2 = list2.next;
            }
            else if(list1 != null && list2 == null) {
                cur.next = new ListNode(list1.val);
                list1 = list1.next;
            }
            //只剩下两个都存在的情况了
            //两个都不存在就进来循环了
            else {
                if(list1.val<list2.val) {
                    cur.next = new ListNode(list1.val);
                    list1 = list1.next; 
                }
                else {
                    cur.next = new ListNode(list2.val);
                    list2 = list2.next;
                }
            }
            cur = cur.next;
        }
        return list.next;
    }
}
相关推荐
IronMurphy4 分钟前
【算法二十九】 437. 路径总和 III
算法·深度优先
2501_908329855 分钟前
C++安全编程指南
开发语言·c++·算法
计算机安禾8 分钟前
【C语言程序设计】第39篇:预处理器与宏定义
c语言·开发语言·c++·vscode·算法·visual studio code·visual studio
参.商.10 分钟前
【Day43】49. 字母异位词分组
leetcode·golang
m0_5698814719 分钟前
C++中的装饰器模式变体
开发语言·c++·算法
笒鬼鬼20 分钟前
【API接口】最新可用红果短剧接口
算法·api·笒鬼鬼·红果短剧·接口源码
weixin_4219226921 分钟前
C++与边缘计算
开发语言·c++·算法
2401_8319207424 分钟前
C++编译期数组操作
开发语言·c++·算法
肆忆_27 分钟前
【面试】手撕线程池
面试
wangfpp28 分钟前
性能优化,请先停手:为什么我劝你别上来就搞优化?
前端·javascript·面试