合并两个有序链表

来源:互联网 发布:dd windows iso 编辑:程序博客网 时间:2024/06/05 01:31

合并两个有序链表,合并以后的链表依旧有序。
代码:

#include <windows.h>#include <iostream>using namespace std;typedef struct Node{    Node(const int& value)        :_or(value)        ,_pNext(NULL)    {}    int _or;    Node* _pNext;}Node;class OrderNode{public:    OrderNode()        :_pHead(NULL)    {}    bool Insert(const int& value)    {        if(_pHead == NULL)        {            _pHead = new Node(value);            return true;        }        Node* pCur = _pHead;        Node* pPre = NULL;        while(pCur)        {            if(pCur->_or <= value)            {                pPre = pCur;                pCur = pCur->_pNext;            }            else                break;        }        Node* pTmp = new Node(value);        if(pCur)//表明是break的,则此时的pCur > value,需要将value插入到pCur之前        {            pTmp->_pNext = pCur;        }        //如果pCur为空,则只需将pTmp插入到pPre之后。        if(pCur == _pHead)            _pHead = pTmp;        else            pPre->_pNext = pTmp;        return true;    }    void print()    {        Node* pCur = _pHead;        while(pCur)        {            cout<<pCur->_or<<" ";            pCur = pCur->_pNext;        }        cout<<endl;    }    Node* Union(OrderNode& or)    {        Node* pNode = or._pHead;        if(NULL == pNode)        {            return _pHead;        }        Node* pCur = _pHead;        Node* pPre = NULL;        while(pCur && pNode)        {            if(pCur->_or < pNode->_or)//or1 < or2 ,将or1向下移动直到or1 > or2,再将or2连接到or1的前一个            {                pPre = pCur;                pCur = pCur->_pNext;            }            else//此时or1 > or2,需要将or2连接到or1的前一个            {                Node* pTmp = new Node(pNode->_or);                pTmp->_pNext = pCur;                if(_pHead == pCur)//如果头结点                    _pHead = pTmp;                else                {                    pPre->_pNext = pTmp;                }                pNode = pNode->_pNext;            }        }        while(pNode)        {            Node* pTmp = new Node(pNode->_or);            pPre->_pNext = pTmp;            pPre = pPre->_pNext;            pNode = pNode->_pNext;        }        return _pHead;    }private:    Node* _pHead;};void FunTest(){    int arr1[]={1,18,6,72,9,43,27,0};    int arr2[]={0,65,4,34,7,87};    int i = 0;    OrderNode or1;    OrderNode or2;    for(;i<sizeof(arr1)/sizeof(arr1[0]); i++)    {        or1.Insert(arr1[i]);    }    for(i=0;i<sizeof(arr2)/sizeof(arr2[0]); i++)    {        or2.Insert(arr2[i]);    }    cout<<"Node1 before:";or1.print();    cout<<"Node2 before:";or2.print();    //or1.Union(or2);    or2.Union(or1);    or1.Union(or2);    //cout<<"Node1 after:";or1.print();    cout<<"Node2 after:";or2.print();}

这里写图片描述

原创粉丝点击