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 *res,*p1,*p2,*tail;
        p1 = l1;
        p2 = l2;
        if(p1 == NULL||p2 == NULL)
        {
            if(p1 == NULL)
            return p2;
            else
            return p1;
        }

           if((p1->val)>(p2->val))
           {
               res = p2;
               p2 = p2->next;

           }

           else
           {
               res = p1;
               p1 = p1->next;
           }

        tail=res;

        while(p1 != NULL && p2 != NULL)
        {

           if((p1->val)>(p2->val))
           {
               tail->next = p2;
               tail = tail->next;//开始出错忘记这一步
               p2 = p2->next;
           }

           else
           {
               tail->next = p1;
               tail = tail->next;
               p1 = p1->next;
           }

        }

        if(p1==NULL)
        tail->next=p2;
        else
        tail->next=p1;
        return res;

    }
};
posted @ 2015-11-28 20:43  djiankuo  阅读(131)  评论(0编辑  收藏  举报