算法 链表相邻元素翻转

链表相邻元素翻转,如a->b->c->d->e->f-g,翻转后变为:b->a->d->c->f->e->g。

关键是在于相邻的两个指针的交换过程。

#include <iostream>


using namespace std;

typedef struct _NodeL
{
    int _data;
    _NodeL *_next;
} NodeL;

NodeL* swapNode(NodeL* &p, NodeL* pPreLeft)
{
    NodeL* pTmp = NULL;
    NodeL* pLeft = NULL;
    NodeL* pRight = NULL;

    if ((p!= NULL) && (p->_next != NULL))
    {
        pLeft = p;
        pRight = p->_next;

        if (pPreLeft!= NULL)
        {
            pPreLeft->_next = pRight;
        }

        pLeft->_next = pRight->_next;
        pRight->_next = pLeft;

        p = pRight;
    }

    return pLeft;
}

void main()
{
    int Test[] = {1,2,3,4,5,6,7,8};
    int i = 0;
    NodeL* Header = NULL;
    NodeL* pNew = NULL;
    NodeL* pTail = NULL;

    for (i=0;i<8;i++)
    {
        pNew = new NodeL();
        pNew->_data = Test[i];
        pNew->_next = NULL;

        if (i == 0)
        {
            Header = pNew;
            pTail = pNew;
        }
        else
        {
            pTail->_next = pNew;
            pTail = pTail->_next;
        }
    }

    pTail = Header;
    while(pTail!=NULL)
    {
        cout << pTail->_data << ", ";
        pTail = pTail->_next;
    }

    pTail = Header;
    while(pTail!=NULL)
    {
        if (pTail == Header)
        {
            swapNode(pTail, NULL);
            Header = pTail;
            pTail = Header->_next;
        }
        else
        {
            pTail = swapNode(pTail->_next, pTail);
        }
    }

    cout << endl;

    pTail = Header;
    while(pTail!=NULL)
    {
        cout << pTail->_data << ", ";
        pTail = pTail->_next;
    }

    cin>>i;
}

你可能感兴趣的:(算法)