• Merge Two Sorted Lists


    1、题目

    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

    2、求解

    public class Node {
        public int data;
        public Node next;
        public Node(int num) {
            this.data = num;
            this.next = null;
        }
    }
    

     public static Node merge(Node head1, Node head2) {
            //创建一个合并的列表
            Node mergedList = null;
            if(head1 == null) {
                return head2;
            }
            if(head2 == null) {
                return head1;
            }
            if(head1.data < head2.data) {
                //移动合并列表的指针
                mergedList = head1;
                //递归比较
                mergedList.next = merge(head1.next, head2);
            } else {
                mergedList = head2;
                mergedList.next = merge(head1, head2.next);
            }
            return mergedList;
        }

    此方法的亮点在于使用递归的方法比较


    欢迎关注我的公众号:小秋的博客 CSDN博客:https://blog.csdn.net/xiaoqiu_cr github:https://github.com/crr121 联系邮箱:rongchen633@gmail.com 有什么问题可以给我留言噢~
  • 相关阅读:
    第11次作业
    第十次实验
    第九次作业
    第八次实验
    第七次作业
    第六次作业
    作业
    JAVA实验三
    JAVA实验二
    JAVA实验一
  • 原文地址:https://www.cnblogs.com/flyingcr/p/10326892.html
Copyright © 2020-2023  润新知