0
点赞
收藏
分享

微信扫一扫

leetcode(21)合并两个有序链表

驚鴻飛雪 2022-04-16 阅读 56
算法

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

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode head = new ListNode(-1);
        ListNode pre = head;

        while(list1 != null && list2 != null){
            if(list1.val >= list2.val){
                pre.next = list2;
                list2 = list2.next;
            }else{
                pre.next = list1;
                list1 = list1.next;
            }
            pre = pre.next;
        }
        pre.next = list1 ==null ? list2:list1;
        return head.next;
    }
}
举报

相关推荐

0 条评论