zoukankan      html  css  js  c++  java
  • 合并两个有序链表(剑指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 }
  • 相关阅读:
    通过注册表设置指定用户启动项的权限
    音频知识学习
    回老家也不忘老本......
    探索DOMNode
    表单填写示例(通过JavaScript访问DOM)
    最近的一些感悟
    C#和Java中的Substring()
    验证ASP.NET页生命周期时间的触发顺序
    解析c语言背后的汇编代码
    oracle nvl()函数在使用中出现的问题
  • 原文地址:https://www.cnblogs.com/yzhengy/p/13225901.html
Copyright © 2011-2022 走看看