您的位置:首页 > 编程语言 > C语言/C++

左神的书——《程序员代码面试指南》之逆置单链表或双链表 c++实现

2017-01-05 14:32 344 查看
////题目:

////逆置单链表

//

////思路:

////首先断言链表不为空,如果只有一节点,不需要逆置,直接返回,

////如果节点数目大于一个时,创建三个变量,从第二个节点开始逆置,pcur指向当前节点,pPre指向前一个节点,pNext指向后一个节点,三个指针同步移动。
//

#include<iostream>
using namespace std ;
#include <cassert>

struct Node
{
int value;
struct Node * Next;

Node(int data):value(data),Next(NULL) { }
};

void Reverse(Node* & pHead)
{
assert(pHead);

if (pHead->Next == NULL)
{
return;
}

Node * pCur = pHead->Next;
Node * pPre = pHead;

while (pCur)
{
Node *pNext = pCur->Next;
pCur->Next = pPre;
pPre = pCur;
pCur = pNext;
}

//最后别忘了将原头指针的next置为空,头指针指向原链表的最后一个节点。

pHead->Next = NULL;
pHead = pPre;

}

int main()
{
//这里只是单纯的分配节点,不释放节点,要不然篇幅太长了。毕竟节点的分配和释放不是重点。
Node *n1 = new Node(1);
Node *n2 = new Node(2);
Node *n3 = new Node(3);
Node *n4 = new Node(4);
Node *n5 = new Node(5);
Node *n6 = new Node(6);
Node *pHead1 = n1;
n1->Next = n2;
n2->Next = n3;
n3->Next = n4;
n4->Next = n5;
n5->Next = n6;

Reverse(pHead1);
Node *pCur = pHead1;
while (pCur)
{
cout << pCur->value <<endl;
pCur = pCur->Next;
}

cout << "hello..." <<endl;
system("pause");
return 0;
}

//进阶题目:

//逆置双向链表。
#include<iostream>
using  namespace std ;
#include <cassert>

struct Node
{
int _value;
struct Node * _pNext;
struct Node * _pPre;

Node (int value):_value(value),_pNext(NULL),_pPre(NULL) { }

};

void ReverseDoubleList(Node* &pHead)
{
assert (pHead);

if (pHead->_pNext == NULL)  //只有一个节点不需要逆置。
{
return;
}

Node *pCur = pHead;
Node *pPre =  NULL;

while (pCur)
{
Node * pNext = pCur->_pNext;
pCur->_pNext = pPre;
pCur->_pPre = pNext;
pPre = pCur;
pCur = pNext;
}

//修改头指针的指向。
pHead = pPre;

}

int main()
{

//这里只是单纯的分配节点,不释放节点,要不然篇幅太长了。毕竟节点的分配和释放不是重点。
Node *n1 = new Node(1);
Node *n2 = new Node(2);
Node *n3 = new Node(3);
Node *n4 = new Node(4);
Node *n5 = new Node(5);
Node *n6 = new Node(6);
Node *pHead1 = n1;
n1->_pNext = n2;
n1->_pPre = NULL;
n2->_pNext = n3;
n2->_pPre = n1;
n3->_pNext = n4;
n3->_pPre = n2;
n4->_pNext = n5;
n4->_pPre = n3;
n5->_pNext = n6;
n5->_pPre = n4;
n6->_pNext = NULL;
n6->_pPre = n5;

ReverseDoubleList(pHead1);
Node *pCur = pHead1;
while (pCur)
{
cout << pCur->_value <<endl;
pCur = pCur->_pNext;
}

cout << "hello..." <<endl;
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐