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

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

    思路:可以有两种实现方法,第一种是通过递归来实现,第二种是通过非递归来实现。

    public class Solution {
        public ListNode Merge(ListNode list1,ListNode list2) {
            if(list1 == null && list2 == null){
                return null;
            }
            if(list1 == null && list2!=null){
                return list2;
            }
            if(list1!=null&&list2==null){
                return list1;
            }
            ListNode merge = null;
            if(list1.val <list2.val){
                merge = list1;
                merge.next = Merge(list1.next,list2);            
            }else{
                merge = list2;
                merge.next = Merge(list1,list2.next);
            }
            return merge;
        }
    }

    非递归:

    public ListNode Merge(ListNode list1,ListNode list2) {
            if(list1 == null && list2 == null){
                return null;
            }
            if(list1 == null && list2!=null){
                return list2;
            }
            if(list1!=null&&list2==null){
                return list1;
            }
            ListNode merge = null;
            ListNode merge2 = null;
            while(list1!=null &&list2!=null){
                if(list1.val<list2.val){
                    if(merge == null){
                        merge2 = merge = list1; //确保头节点
                    }else{
                        merge.next = list1;
                        merge = merge.next;
                    }
                    list1 = list1.next;
                }else{
                    if(merge == null){
                        merge2 = merge = list2;
                    }else{
                        merge.next = list2;
                        merge = merge.next; //这个也要移位
                    }
                    list2 = list2.next;
                }
            }
            if(list1!=null){
                merge.next = list1; //节点赋值即可
            }
            if(list2!=null){
                merge.next = list2;
            }
            return merge2;
        }
    

      

  • 相关阅读:
    java方法执行超时关闭
    PostGIS-将多面转换为单面(PostGIS
    deepin安装JDK
    Power Designer反向工程
    【Redis实操】twemproxy代理搭建
    mysql 一些语句
    利用insertd查出更新记录
    sqlserver 存储过程分页
    sqlserver存储过程分页记录
    js group by
  • 原文地址:https://www.cnblogs.com/yingpu/p/5819613.html
Copyright © 2011-2022 走看看