代码改变世界

leetcode - Merge Two Sorted Lists

2013-10-20 10:43  张汉生  阅读(122)  评论(0编辑  收藏  举报

/**
 * 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) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if (l1==NULL)
            return l2;
        if (l2==NULL)
            return l1;
        ListNode * head=NULL, *curNode,*lastNode;
        while (!(l1==NULL || l2==NULL)){ // "l1 != NULL && l2 != NULL" warning and runtime error, why?
            if (l1->val <= l2->val){
                curNode = l1;
                l1 = l1->next;
            }
            else {
                curNode = l2;
                l2 = l2->next;
            }
            if (head==NULL)
                head = curNode;
            else 
                lastNode->next = curNode;
            lastNode = curNode;
        }
        if (l2!=NULL)
            lastNode->next = l2;
        if (l1!=NULL)
            lastNode->next = l1;
        return head;
    }
};