题解 | #合并两个排序的链表#

合并两个排序的链表

https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode Merge(ListNode list1, ListNode list2) {
        if (list1 == null) return list2;
        if (list2 == null) return list1;
        ListNode dummyNode = new ListNode(-1);
        ListNode first = dummyNode;
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                first.next = new ListNode(list1.val);
                list1 = list1.next;
            } else {
                first.next = new ListNode(list2.val);
                list2 = list2.next;
            }
            first = first.next;
        }

        while (list1 != null) {
            first.next = new ListNode(list1.val);
            list1 = list1.next;
            first = first.next;
        }
        while (list2 != null) {
            first.next = new ListNode(list2.val);
            list2 = list2.next;
            first = first.next;
        }
        return dummyNode.next;
    }
}

解题思想:虚拟节点+循环遍历比较+剩余节点遍历

#算法##算法笔记#
全部评论

相关推荐

头像
02-26 13:58
门头沟学院 Java
北城_阿亮:把八股背一背,包装一下实习经历项目经历,要是有心思考证就考一考,然后把别人的项目爬到自己github上,包装到简历里,什么三个月?一个月!
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务