剑指offer_合并两个排序的链表

题目描述

 

 方法一:按部就班算

 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 memo=head;
14         while(list1!=null||list2!=null){
15             if(list1==null){
16                 ListNode m=new ListNode(list2.val);
17                 list2=list2.next;
18                 head.next=m;
19                 head=head.next;
20                 continue;
21             } 
22             if(list2==null){
23                 ListNode m=new ListNode(list1.val);
24                 list1=list1.next;
25                 head.next=m;
26                 head=head.next;
27                 continue;
28             } 
29             if(list1.val < list2.val){
30                 ListNode m=new ListNode(list1.val);
31                 list1=list1.next;
32                 head.next=m;
33                 head=head.next;
34             }
35             else{
36                 ListNode m=new ListNode(list2.val);
37                 list2=list2.next;
38                 head.next=m;
39                 head=head.next;
40             }
41             
42         }
43         return memo.next;
44     }
45 }

方法二:递归

 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.val<=list2.val){
15            list1.next=Merge(list1.next,list2);
16            return list1;
17        }else{
18            list2.next=Merge(list1,list2.next);
19            return list2;
20        }
21        
22     }
23 }

 

posted @ 2019-08-29 21:43  chyblogs  阅读(100)  评论(0)    收藏  举报