您的位置:首页 > 其它

算法 链表相邻元素翻转

2015-08-27 08:11 274 查看
链表相邻元素翻转,如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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: