Merge Two Sorted Lists

来源:互联网 发布:js删除节点的方法 编辑:程序博客网 时间:2024/05/29 17:22

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 *p1=l1, *p2 = l2;        ListNode *head,*cur;        if(l1==NULL || l2 == NULL){            return l1==NULL?(l2==NULL?NULL:l2):l1;        }        if(p1->val > p2->val){            head = p2;            p2 = p2->next;        }        else{            head = p1;            p1 = p1->next;        }        cur = head;        while(p1 !=NULL && p2 != NULL){            if(p1->val > p2->val){                cur->next = p2;                p2 = p2->next;            }            else{                cur->next = p1;                p1 = p1->next;            }            cur = cur ->next;        }        while(p1!=NULL){            cur ->next = p1;            cur = cur ->next;            p1 = p1->next;        }        while(p2!=NULL){            cur -> next = p2;            cur = cur ->next;            p2 = p2->next;        }        cur ->next = NULL;        return head;     }};
0 0