合并俩个已排序的链表

来源:互联网 发布:共空间模式算法 编辑:程序博客网 时间:2024/05/29 18:21

非递归

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {        if(l1==NULL)            return l2;        if(l2==NULL)            return l1;        ListNode* root=new ListNode(0);        ListNode* pre=root;        ListNode* p=l1;        ListNode* q=l2;        while(p && q){            if(p->val < q->val){                pre->next=p;                p=p->next;            }else{                pre->next=q;                q=q->next;            }            pre=pre->next;        }        /*        while(p){            pre->next=p;            pre=pre->next;            p=p->next;        }        while(q){            pre->next=q;            pre=pre->next;            q=q->next;        }*/        pre->next= p!=NULL ? p:q;        return root->next;    }




代码: 递归

 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {        if(l1==NULL)            return l2;        if(l2==NULL)            return l1;        if(l1->val < l2->val){            l1->next=mergeTwoLists(l1->next,l2);            return l1;        }else{            l2->next=mergeTwoLists(l1,l2->next);            return l2;        }    }