C++实现两个有序链表合并(17)---《那些奇怪的算法》

来源:互联网 发布:药监局数据库 编辑:程序博客网 时间:2024/06/16 11:21

这种代码有点类似于归并排序的合并阶段,大家可以对应参考起来进行学习!
ListNode结构

struct ListNode {    int val;    struct ListNode *next;    ListNode(int x) :            val(x), next(NULL) {    }};

迭代版本:

class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { if(pHead1==NULL) return pHead2; if(pHead2==NULL) return pHead1; ListNode* root=NULL; ListNode* pre=NULL; while(pHead1&&pHead2){ if(root==NULL){ if(pHead1->val<=pHead2->val){ root=pre=pHead1; pHead1=pHead1->next; }else{ root=pre=pHead2; pHead2=pHead2->next; } }else{ ListNode* cur=NULL; if(pHead1->val<=pHead2->val){ cur=pHead1; pHead1=pHead1->next; }else{ cur=pHead2; pHead2=pHead2->next; } pre->next=cur; pre=cur; } } if(pHead1){ pre->next=pHead1; } if(pHead2){ pre->next=pHead2; } return root; } };

递归版本:

class Solution {public:    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)    {        if(!pHead1) return pHead2;        if(!pHead2) return pHead1;        ListNode *node;        if(pHead1->val<=pHead2->val){            node=new ListNode(pHead1->val);            node->next=Merge(pHead1->next,pHead2);        }else{            node=new ListNode(pHead2->val);            node->next=Merge(pHead1,pHead2->next);        }        return node;    }};
原创粉丝点击