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

    题目:合并两个排序的链表

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

    思路;这个题感觉没啥难的,就是分情况讨论下,有循环有递归两种做法

     1 public class Solution {
     2     public ListNode Merge(ListNode list1,ListNode list2) {
     3      if(list1==null&&list2==null) return null;
     4      if(list1==null)return list2;
     5      if(list2==null)return list1;
     6         ListNode head=new ListNode(0);
     7         head.next=null;
     8         ListNode root=head;
     9         while(list1!=null&&list2!=null){
    10          if(list1.val<=list2.val){
    11              head.next=list1;
    12               head=head.next;;
    13              list1=list1.next;
    14             
    15          }
    16           else if(list2.val<list1.val){
    17              head.next=list2;
    18                head=head.next;
    19              list2=list2.next;
    20                
    21          }  
    22         }
    23         
    24         if(list1!=null) head.next=list1;
    25         if(list2!=null)head.next=list2;
    26         return root.next;
    27     }
    28 }

    再来个递归的

     1 public class Solution {
     2     public ListNode Merge(ListNode list1,ListNode list2) {
     3      if(list1==null)return list2;
     4      if(list2==null)return list1;
     5       if(list1.val<=list2.val){
     6           list1.next=Merge(list1.next,list2);
     7           return list1;
     8       }
     9         if(list2.val<list1.val){
    10             list2.next=Merge(list1,list2.next);
    11             return list2;
    12         }
    13         return null;
    14     }
    15 }
  • 相关阅读:
    Windows Driver Mode 1
    一个程序员的奋斗经历 2
    JavaScript判断文件是否存在
    流程图个图标详解
    wget for windows
    软件的开发周期
    Firefox支持activex的插件
    第二次作业
    C/C++字符串使用整理
    c#学习小记录(1)
  • 原文地址:https://www.cnblogs.com/pathjh/p/9140989.html
Copyright © 2011-2022 走看看