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

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

     其实思路跟归并排序差不多,注意边界值

        1.两个List都为空,则返回空
        2.其中一个List为空,则返回不为空的List

     循环解法:

    public static ListNode merge(ListNode list1,ListNode list2) {
    		if(list1==null||list2==null) {
    			if(list1==null) {
    				return list2;
    			} else if (list2==null) {
    				return list1;
    			} else {
    				return null;
    			}
    		}
    		ListNode leftCurrent=list1;
    		ListNode rightCurrent=list2;
    		ListNode prehead=new ListNode(0);
    		ListNode leftPrevious=null;
    		ListNode rightPrevious=null;
    		//先决定谁是头指针
    		if(leftCurrent.val>rightCurrent.val) {
    			prehead.next=rightCurrent;
    			rightPrevious=rightCurrent;
    			rightCurrent=rightCurrent.next;
    		} else {
    			prehead.next=leftCurrent;
    			leftPrevious=leftCurrent;
    			leftCurrent=leftCurrent.next;
    		}
    		//进行合并,当两者都没有到达最后一个点时
    		while(rightCurrent!=null&&leftCurrent!=null) {
    			if(leftCurrent.val>rightCurrent.val) {
    				leftPrevious.next=rightCurrent;
    				rightPrevious=rightCurrent;
    				rightCurrent=rightCurrent.next;
    			} else {
    				rightPrevious.next=leftCurrent;
    				leftPrevious=leftCurrent;
    				leftCurrent=leftCurrent.next;
    			}
    		}
    		//若右边链表不为空
    		if(rightCurrent!=null) {
    			leftPrevious.next=rightCurrent;
    		}
    		//若左边链表不为空
    		if(leftCurrent!=null) {
    			rightPrevious.next=leftCurrent;
    		}
    		return prehead.next;
    }
    

     递归解法:

    public static ListNode merge(ListNode list1,ListNode list2) {
    		if(list1==null||list2==null) {
    			if(list1==null) {
    				return list2;
    			} else if (list2==null) {
    				return list1;
    			} else {
    				return null;
    			}
    		}
    		if(list1.val>list2.val) {
    			list2.next=merge(list1,list2.next);
    			return list2;
    		}  else {
    			list1.next=merge(list1.next,list2);
    			return list1;
    		}
    }
    

      

  • 相关阅读:
    nginx centos 服务开机启动设置实例详解
    CentOS打开关闭永久防火墙指定端口
    使用 nginx 反向代理 sqlserver 访问 配置
    Springboot集成Mybatis
    linux中查看java进程
    mybatis关于jdbc连接报错,5.5.62MySQL连接,出现com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure等问题解决方法
    索引的分析
    MySQL慢查询分析工具
    MySQL锁
    nGrinder介绍、编写脚本与执行(完整版)
  • 原文地址:https://www.cnblogs.com/qingfei1994/p/4894711.html
Copyright © 2011-2022 走看看