zoukankan      html  css  js  c++  java
  • 合并2个排序的链表

    描述

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

    解析

    节点依次比较,指针移动。类似归并的merge方法,思路一样。

    代码

    /*
    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 (null == list1 && null == list2) {
                return null;
            } else if (null == list1) {
                return list2;
            } else if (null == list2) {
                return list1;
            }
            //设置一个头节点
            ListNode newListNode = new ListNode(0);
            ListNode root = newListNode;
            while (null != list1 && null != list2) {
                if (list1.val < list2.val) {
                    newListNode.next = list1;
                    newListNode = list1;
                    list1 = list1.next;
                } else {
                    newListNode.next = list2;
                    newListNode = list2;
                    list2 = list2.next;
                }
            }
            if (null != list1) {
                newListNode.next = list1;
            }
            if (null != list2) {
                newListNode.next = list2;
            }
            return root.next;
        }
    }
  • 相关阅读:
    解决git推不上去1
    django中CBV源码分析
    Form和ModelForm组件
    jquery操作cookie
    django中的中间件
    django中ORM中锁和事务
    django_ajax
    docker安装jenkins 容器,集成python环境
    支付宝第三方支付
    redis基本使用
  • 原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/10768627.html
Copyright © 2011-2022 走看看