LintCode:合并两个排序链表

LintCode:合并两个排序链表

/** * 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 && l2 !=NULL){
            return l2;
        }
        if(l1!=NULL && l2 == NULL){
            return l1;
        }
        ListNode *p1 = l1;
        ListNode *p2 = l2;
        while(p1->next != NULL){
            p1 = p1->next;
        }
        p1->next = p2;
        for(ListNode *p3 = l1; p3!=NULL; p3=p3->next){
            for(ListNode *p4=p3;p4!=NULL; p4=p4->next){
                if(p3->val>p4->val){
                    int tmp = p3->val;
                    p3->val = p4->val;
                    p4->val = tmp;
                }
            }
        }
        return l1;
    }
};

你可能感兴趣的:(链表,合并)