剑指Offer第十六题:合并两个排序的链表

合并两个排序的链表

https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337?tpId=13&tqId=11169&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

解答:
1.遍历两个链表,按大小顺序拼接。
public class Q_16 {

public ListNode Merge(ListNode list1, ListNode list2) {
    ListNode head = new ListNode(0);
    ListNode movnode = head;

    while (list1 != null && list2 != null) {
        if (list1.val > list2.val) {
            movnode.next = list2;
            list2 = list2.next;
        } else {
            movnode.next = list1;
            list1 = list1.next;
        }
        movnode = movnode.next;
    }
    if (list1 != null) {
        movnode.next = list1;
    }
    if (list2 != null) {
        movnode.next = list2;
    }
    return head.next;
}

}

2.递归
public class Q_16 {

//递归
public ListNode Merge1(ListNode list1, ListNode list2) {
    if (list1 == null) {
        return list2;
    } else if (list2 == null) {
        return list1;
    }else{
        if(list1.val<list2.val){
            list1.next=Merge1(list1.next, list2);
            return list1;
        }else {
            list2.next=Merge1(list1, list2.next);
            return list2;
        }
    }
}

}

全部评论
大佬,为什么开始要声明 ListNode head = new ListNode(0); ListNode movnode = head; 这个声明没看太懂,然后最后的返回也不太懂,为什么不返回movnode呢? return head.next;
1 回复 分享
发布于 2021-04-14 20:14
大佬,为什么我的编译器总是让我最后return,而不能在if/else域里return
点赞 回复 分享
发布于 2021-05-21 10:37
最后movenode移到了尾部,head只是一个标识,为了简化循环和标记头部
点赞 回复 分享
发布于 2021-05-16 09:14

相关推荐

07-02 10:39
门头沟学院 Java
Steven267:说点真实的,都要秋招了,还没有实习,早干嘛去了,本来学历就差,现在知道急了,而且你这个简历完全可以写成一页,劣势太大了,建议转测试
点赞 评论 收藏
分享
06-07 12:20
新余学院 Java
点赞 评论 收藏
分享
评论
26
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务