21. 合并两个有序链表

题目描述

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

方法 暴力算法

先判断是否有一个为空,有则直接返回另一个即可
新创建一个链表存储排序后的结果集
将都不会null的值进行比较,存放
最后如果某个链表不会空,直接放在结果集后面即可

代码

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1 == null || list2 == null) return list1 == null ? list2 : list1;
        ListNode head = new ListNode(-1);
        head.next = list1;
        ListNode cur = head;
        while (list1 != null && list2 != null) {
            if(list1.val <= list2.val) {
                cur.next = list1;
                cur = cur.next;
                list1 = list1.next;
            } else {
                cur.next = list2;
                cur = cur.next;
                list2 = list2.next;
            }
        }

        if(list1 != null) {
            cur.next = list1;
        }

        if(list2 != null) {
            cur.next = list2;
        }

        return head.next;
    }
}