LeetCode题目:Merge Two Sorted Lists

By | 2012 年 10 月 5 日

Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.



代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        ListNode *proot = NULL;
        ListNode **pplast = &proot;
        while(l1 || l2){
            if(l1) {
                ListNode *minNode;
                if(!l2 || l1->val <= l2->val){
                    //l1 is min
                    minNode = l1;
                    l1 = l1->next;
                } else if(l2) {
                    //l2 is min
                    minNode = l2;
                    l2 = l2->next;
                }
                //proceed root
                *pplast = minNode;
                pplast = &(minNode->next);
            } else {
                //l1 is empty
                *pplast = l2;
                break;
            }
        }
        return proot;
    }
};

One thought on “LeetCode题目:Merge Two Sorted Lists

  1. Pingback: LeetCode题目:Merge k Sorted Lists - uniEagle

发表评论

电子邮件地址不会被公开。 必填项已用*标注