两个有序链表的合并

来源:互联网 发布:java项目开发全过程 编辑:程序博客网 时间:2024/06/11 08:48

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
1.递归方法

struct ListNode {    int val;    struct ListNode *next;    ListNode(int x) :            val(x), next(NULL) {    }};ListNode* Merge(ListNode* pHead1, ListNode* pHead2)    {        if(pHead1==NULL)            return pHead2;        else if(pHead2==NULL)            return pHead1;        ListNode *pHead;        if(pHead1->val<pHead2->val){            pHead=pHead1;            pHead->next=Merge(pHead1->next,pHead2);        }        else{            pHead=pHead2;            pHead->next=Merge(pHead1,pHead2->next);        }        return pHead;    }

2.非递归方法

ListNode* Merge(ListNode* pHead1, ListNode* pHead2)    {        if(pHead1==NULL)            return pHead2;        else if(pHead2==NULL)            return pHead1;        ListNode *pHead;        //先设置第一个节点        if(pHead1->val < pHead2->val){           pHead=pHead1;           pHead1=pHead1->next;        }        else{           pHead=pHead2;           pHead2=pHead2->next;        }        ListNode *temp=pHead;//最终要将pHead返回,所以应将其记录        //依次比较节点的大小,直到一个链表遍历完为止        while(pHead1 && pHead2){            if(pHead1->val < pHead2->val){                temp->next=pHead1;                pHead1=pHead1->next;            }            else{                temp->next=pHead2;                pHead2=pHead2->next;            }            temp=temp->next;        }        //连接剩余的节点        if(pHead1==NULL){            temp->next=pHead2;        }        if(pHead2==NULL){           temp->next=pHead1;        }        return pHead;    }
原创粉丝点击