将两个排序链表合并为一个新的排序链表

2016-08-12  本文已影响15人  杰米
/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param ListNode l1 is the head of the linked list
     * @param ListNode l2 is the head of the linked list
     * @return: ListNode head of linked list
     */
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        // write your code here
        if (l1 == NULL) {
            return l2;
        } 
        if(l2 == NULL) {
            return l1;
        }
        
        ListNode *maxHead;
        
        if (l1->val < l2->val) {
            maxHead = l1;
            maxHead->next = mergeTwoLists(l1->next,l2);
        } else {
            maxHead = l2;
            maxHead->next = mergeTwoLists(l1,l2->next);
        }
        
        return maxHead;
        
    }
};
上一篇 下一篇

猜你喜欢

热点阅读