合并两个有序单链表

typedef struct Node
{
    Node(const int& value)
    : m_value(value)
    , m_pNext(NULL)
    {}
    int   m_value;
    Node* m_pNext;
}Node, *pNode ;

class List
{
public:
    List()
        : _pHead(NULL)
        , _pTail(NULL)
    {}
    void PushBack(const int& value)
    {
        if (_pHead == NULL)
        {
            _pHead = _pTail = _BuyNode(value);
        }
        else
        {
            Node* temp = _BuyNode(value);
            _pTail->m_pNext = temp;
            _pTail = temp;
        }
    }

    pNode* CombineList(List pHead1, List pHead2)
    {
        if (pHead1._pHead == NULL || pHead2._pHead == NULL)
            return NULL;
        if (pHead1._pHead == NULL)
            return &pHead2._pHead;
        if (pHead2._pHead == NULL)
            return &pHead1._pHead;
        pNode pNewHead = NULL;
        pNode pHead1Next = pHead1._pHead->m_pNext;
        pNode pHead2Next = pHead2._pHead->m_pNext;
        if (pHead1._pHead->m_value < pHead2._pHead->m_value)
        {
            pNewHead = pHead1._pHead;
            pHead1._pHead = pHead1Next;
            if (pHead1Next)
                pHead1Next = pHead1Next->m_pNext;
            pNewHead->m_pNext = NULL;
        }
        else
        {
            pNewHead = pHead2._pHead;
            pHead2._pHead = pHead2Next;
            if (pHead2Next)
                pHead2Next = pHead2Next->m_pNext;
            pNewHead->m_pNext = NULL;
        }
        pNode pNew = pNewHead;
        while (pHead1._pHead&&pHead2._pHead)
        {
            if (pHead1._pHead->m_value < pHead2._pHead->m_value)
            {
                pNew->m_pNext = pHead1._pHead;
                pHead1._pHead = pHead1Next;
                if (pHead1Next)
                    pHead1Next = pHead1Next->m_pNext;
            }
            else
            {
                pNew->m_pNext = pHead2._pHead;
                pHead2._pHead = pHead2Next;
                if (pHead2Next)
                    pHead2Next = pHead2Next->m_pNext;
            }
            pNew = pNew->m_pNext;
        }
        if (pHead1._pHead)
            pNew->m_pNext = pHead1._pHead;
        if (pHead2._pHead)
            pNew->m_pNext = pHead2._pHead;
        return &pNewHead;
    }

private:
    pNode _BuyNode(const int& value)
    {
        return new Node(value);
    }
private:
    pNode _pHead;
    pNode _pTail;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值