• 合并两个有序链表(剑指offer-16)


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

    解答
    方法1:递归

     1 /*
     2 public class ListNode {
     3     int val;
     4     ListNode next = null;
     5 
     6     ListNode(int val) {
     7         this.val = val;
     8     }
     9 }*/
    10 public class Solution {
    11     public ListNode Merge(ListNode list1,ListNode list2) {
    12         if(list1 == null) return list2;//递归终止条件
    13         if(list2 == null) return list1;//递归终止条件
    14         if(list1 == null && list2 == null) return null;//递归终止条件
    15         ListNode head = null;
    16         if(list1.val>=list2.val){
    17             head = list2;
    18             list2.next = Merge(list1,list2.next);}
    19         else{
    20             head = list1;
    21             list1.next = Merge(list1.next,list2);}
    22         return head;
    23     }
    24 }


    图片引用自:https://blog.csdn.net/fengpojian/article/details/81384130

    方法2:迭代

     1 /*
     2 public class ListNode {
     3     int val;
     4     ListNode next = null;
     5 
     6     ListNode(int val) {
     7         this.val = val;
     8     }
     9 }*/
    10 public class Solution {
    11     public ListNode Merge(ListNode list1,ListNode list2) {
    12         ListNode head = new ListNode(-1);
    13         ListNode cur = head;
    14         while (list1 != null && list2 != null) {
    15         if (list1.val <= list2.val) {
    16             cur.next = list1;
    17             list1 = list1.next;
    18         } else {
    19             cur.next = list2;
    20             list2 = list2.next;
    21         }
    22         cur = cur.next;
    23         }
    24         if (list1 != null)
    25             cur.next = list1;
    26         if (list2 != null)
    27             cur.next = list2;
    28         return head.next;
    29     }
    30 }
  • 相关阅读:
    小作业(# 求1-2+3-4+5 ... 99的所有数的和)
    小作业(3、输出 1-100 内的所有奇数 4、输出 1-100 内的所有偶数)
    小作业(求1-100的所有数的和)
    作业小练习(使用while循环输入 1 2 3 4 5 6 8 9 10)
    keepalived介绍
    nginx日志文件配置
    Nginx配置文件编写实例
    Nginx部署流程
    nginx服务介绍
    http协议原理介绍
  • 原文地址:https://www.cnblogs.com/yzhengy/p/13225901.html
Copyright © 2020-2023  润新知