zoukankan      html  css  js  c++  java
  • 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 有什么问题可以给我留言噢~
  • 相关阅读:
    SQLSERVER Tempdb的作用及优化
    sqlserver分区表索引
    Install the mongdb
    mysql常用参数监控
    Mysql由浅入深
    nginx配置文件优化
    ping主机不通邮件报警
    top结果解释
    了解MQ
    kafka安装部署
  • 原文地址:https://www.cnblogs.com/flyingcr/p/10326892.html
Copyright © 2011-2022 走看看