# C++算法之 反转单链表

struct ListNode

int    m_nValue;

ListNode* m_pNext;

｝;

pNext的作用：用来保存pNode后面一个的节点，防止链表在中间断开，然后pPrev与pNode往下遍历：

ListNode* ReverseList(ListNode* head)
{

ListNode* pPrev = NULL;

while (pNode != NULL)
{
ListNode* pNext = pNode->m_pNext;//保存下一个节点的值

pNode->m_pNext = pPrev;//把当前pNode的下一个节点指向pPrev
pPrev = pNode;//此时pPrev向后移动指向此时的pNode

pNode = pNext;//而pNode也向后移动，指向刚才保存的pNext;
}

return pPrev;

}

// ReverseList.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;
struct ListNode
{
int         m_nValue;
ListNode*   m_pNext;

ListNode()
{

}

ListNode(int i):m_nValue(i),m_pNext(NULL)
{

}
};

{
ListNode* pNew = new ListNode();
pNew->m_nValue = value;
pNew->m_pNext  = NULL;

{
}
else
{
while (pNode->m_pNext!=NULL)
{
pNode = pNode->m_pNext;
}

pNode->m_pNext = pNew;
}
}
{

while (pNode!=NULL)
{
cout<<pNode->m_nValue<<endl;
pNode = pNode->m_pNext;
}
}
{

ListNode* pPrev = NULL;

while (pNode != NULL)
{
ListNode* pNext = pNode->m_pNext;

pNode->m_pNext = pPrev;
pPrev = pNode;

pNode = pNext;
}

return pPrev;

}
int _tmain(int argc, _TCHAR* argv[])
{

/*
ListNode* node1 = new ListNode(2);
ListNode* node2 = new ListNode(3);
ListNode* node3 = new ListNode(4);
ListNode* node4 = new ListNode(5);

node1->m_pNext = node2;
node2->m_pNext = node3;
node3->m_pNext = node4;
node4->m_pNext = NULL;
*/

ListNode* pNode1 = new ListNode(1);
//Print(pNode1);

cout<<"反转以前："<<endl;
Print(pNode1);

ListNode* pNode = ReverseList(pNode1);
cout<<"反转以后"<<endl;
Print(pNode);

getchar();
return 0;
}