LeetCode Top 100 Liked Questions 21. Merge Two Sorted Lists (Java版; Easy)

welcome to my blog

LeetCode Top 100 Liked Questions 21. Merge Two Sorted Lists (Java版; Easy)

题目描述

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
第一次做, 创建临时头结点, 不用分别处理头结点和非头结点; 模拟归并排序的归并过程, 注意不同之处:需要保存上一个节点; while后面是if, 不再是while了; 代码中某四行可以用一行代替 curr.next = left!=? left : right;
/*
创建tempHead, 就不用将头结点和非头结点分开处理了
模拟归并排序的归并过程
*/
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1==null)
            return l2;
        if(l2==null)
            return l1;
        
        ListNode tempHead = new ListNode(0);
        ListNode left=l1, right=l2, curr=tempHead;
        while(left!=null && right!=null){
            if(left.val < right.val){
                curr.next = left;
                left = left.next;
            }
            else{
                curr.next = right;
                right = right.next;
            }
            curr = curr.next;
        }
        /*
        下面四行可以用一行代替
        curr.next = left!=? left : right;
        */
        //这里不是while, 是if!!!
        if(left!=null)
            curr.next = left;
        if(right!=null)
            curr.next = right;
        return tempHead.next;
    }
}
第一次做, 递归版
/*
递归版
递归函数逻辑:找出两个链表中可以作为头结点的节点, 该头结点连接其余部分的头结点
返回值:当前头结点
*/
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        //base case
        if(l1==null)
            return l2;
        if(l2==null)
            return l1;
        //
        ListNode head=null;
        if(l1.val<l2.val){
            head = new ListNode(l1.val);
            head.next = mergeTwoLists(l1.next, l2);
        }
            
        else{
            head = new ListNode(l2.val);
            head.next = mergeTwoLists(l1, l2.next);
        }
        return head;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值