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 有什么问题可以给我留言噢~
  • 相关阅读:
    TP5.1 遇见问题整理
    PDO 基础
    php7 连接 mysql 的两种方式
    [php] 添加接口访问日志(文件)
    curl 向远程服务器传输file文件
    VBoxManage
    linux 系统下安装多个php版本
    vim中文乱码问题
    vim 翻页命令
    php list()函数
  • 原文地址:https://www.cnblogs.com/flyingcr/p/10326892.html
Copyright © 2011-2022 走看看