剑指offer-合并两个排列的链接

题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
 
 1 public ListNode Merge(ListNode list1,ListNode list2) {//链表 my
 2         ListNode head = new ListNode(0);
 3         ListNode cur = head;
 4         while(list1!=null&&list2!=null){
 5             if(list1.val<list2.val){
 6                 cur.next = list1;
 7                 list1 = list1.next;
 8             }
 9             else{
10                 cur.next = list2;
11                 list2=list2.next;
12             }
13             cur = cur.next;
14         }
15         if(null == list1){
16             cur.next =  list2;
17         }
18         if(null == list2){
19             cur.next =  list1;
20         }
21         return head.next;
22     }
使用递归
public ListNode Merge(ListNode list1,ListNode list2) {//链表 递归my
        if(null == list1){
            return list2;
        }
        if(null == list2){
            return list1;
        }
        ListNode result = null;
        if(list1.val <= list2.val){
            result = list1;
            result.next= Merge(list1.next,list2);
        }
        else{
            result = list2;
            result.next=Merge(list1,list2.next);
        }
        return result;
    }
原文地址:https://www.cnblogs.com/zhacai/p/10692134.html