《剑指offer》——合并两个排序的链表

来源:互联网 发布:伦佐皮亚诺 知乎 编辑:程序博客网 时间:2024/05/29 09:01
/*非递归*/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 *pNode1 = pHead1;//遍历链表1的指针    ListNode *pNode2 = pHead2;//遍历链表2的指针    ListNode *pHead = NULL;//指向合并后链表头结点的指针    ListNode *pNode = NULL;//记录头结点的指针    //比较两个链表的第一个结点,找到合并后链表的头结点    if(pNode1 -> val < pNode2 -> val)    {        pHead = pNode1;        pNode1 = pNode1 -> next;    }    else    {        pHead = pNode2;        pNode2 = pNode2 -> next;    }    pNode = pHead;//使用合并后链表的头结点    while(pNode1 && pNode2)//当两个链表都没有遍历结束时    {        if(pNode1 -> val <= pNode2 -> val)        {            pNode -> next = pNode1;//将头结点指向下一个结点            pNode = pNode1;//将下一个结点设置为新的头结点            pNode1 = pNode1 -> next;//将遍历指针后移        }        else        {            pNode -> next = pNode2;            pNode = pNode2;            pNode2 = pNode2 -> next;        }    }    if(pNode1)//如果链表1还有剩余结点        pNode -> next = pNode1;//将头结点指向链表1剩余的结点    if(pNode2)        pNode -> next = pNode2;    return pHead;//返回合并后链表的头结点地址}
/*递归*/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 = NULL;//合并后链表的头结点    //每次循环将头结点指向新找出来的头结点    if(pHead1 -> val < pHead2 -> val)    {        pHead = pHead1;        pHead -> next = Merge(pHead1 -> next, pHead2);    }    else    {        pHead = pHead2;        pHead -> next = Merge(pHead1, pHead -> next);    }    return pHead;//返回合并后的链表的头结点}
0 0
原创粉丝点击