单链表的逆置
非递归实现
#include <iostream>
#include <Windows.h>
using namespace std;
struct ListNode{
int _value;
ListNode* _next;
ListNode(const int& value)
:_value(value)
, _next(NULL)
{}
};
//单链表的逆置 非递归实现
ListNode* ReverseList(ListNode* pHead)
{
if (pHead == NULL)
{
return NULL;
}
if (pHead->_next == NULL)
{
return pHead;
}
ListNode* cur = pHead; //当前头结点
ListNode* ReverseHead = NULL; //逆置后的头结点
ListNode* prev = NULL;
while (cur)
{
ListNode* next = cur->_next;
if (next == NULL)
{
ReverseHead = cur;
}
cur->_next = prev; //逆转的过程,并且能将头结点的prev置为NULL
prev = cur;
cur = next;
}
return ReverseHead;
}
int main()
{
ListNode* pHead = new ListNode(1);
ListNode* p = pHead;
ListNode* q = pHead;
for (int i = 2; i <= 10; ++i)
{
ListNode* temp = new ListNode(i);
p->_next = temp;
p = temp;
}
cout << "原始链表: " << "";
while (q)
{
cout << q->_value << "->";
q = q->_next;
}
cout << endl;
ListNode* ppy = ReverseList(pHead);
cout << "逆转后的链表: " << "";
while (ppy != NULL)
{
cout << ppy->_value << "->";
ppy = ppy->_next;
}
cout << endl;
system("pause");
return 0;
}