Fork me on GitHub

LeetCode 21 Merge Two Sorted Lists (有序两个链表整合)

 
Problem: 已知两个有序链表(链表中的数值递增排列)。将这两个链表进行合并操作,并且满足递增排列 即合并后仍为有序链表。
 
 
递归进行合并操作。mergeTwoList(ListNode list1, ListNode list2)
     当list1==null时 return list2;
     当list2==null时 return list1;
     当list1.val <=list2.val时 ,mergeHead等于list1;mergeHead.next = mergeTwoList(list1.next,list2);
     当list1.val > list2.val 时, mergeHead等于list2;  mergeHead.next = mergeTwoList(list1,list2.next);
 
 
参考代码:
 
package leetcode_50;

/***
 * 
 * @author pengfei_zheng
 * 两个有序链表整合
 */
public class Solution21 {
    public class ListNode {
         int val;
         ListNode next;
         ListNode(int x) { val = x; }
    }
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1 == null){
            return l2;
        }
        if(l2 == null){
            return l1;
        }
        
        ListNode mergeHead;
        if(l1.val <= l2.val){
            mergeHead = l1;
            mergeHead.next = mergeTwoLists(l1.next, l2);
        }
        else{
            mergeHead = l2;
            mergeHead.next = mergeTwoLists(l1, l2.next);
        }
        return mergeHead;
    }
    
}

 

 
posted @ 2017-03-08 13:06  伊甸一点  阅读(224)  评论(0编辑  收藏  举报