这个题目自己至少看了好几遍, 早上起来自己手写了一下,又在电脑上实现了一下,发现最后还是出现了问题。
问题包括:
对当前结点的pNext没有设置,导致最后俩节点出现了循环环;
while条件设置出错,只判断了cur,没有判断cur->pNext;
对一个结点的情形没有考虑到。
// reverNode.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "windows.h"
#include "iostream"
using namespace std;
typedef struct ListNode
{
int mVlaue;
ListNode* pNext;
};
ListNode* reverseList(ListNode* head)
{
if (!head || head->pNext==NULL)
return head;
ListNode* NewHead;
ListNode* pre = NULL;
ListNode* cur = head;
ListNode* Next = NULL;
while (cur!=NULL && cur->pNext!=NULL)
{
if (cur != head)
pre->pNext = cur->pNext;
if (cur == head)
head = cur->pNext;
pre = cur;
Next = cur->pNext->pNext;
cur->pNext->pNext = cur;
cur->pNext = Next;
cur = Next;
}
return head;
}
ListNode* creatList()
{
ListNode* head = NULL;
ListNode* CurNode = head;
for (int i=1;i<=5;i++)
{
ListNode* TempNode = new ListNode;
TempNode->mVlaue = i;
TempNode->pNext = NULL;
if (head == NULL)
{
CurNode = TempNode;
head = TempNode;
}
else
{
CurNode->pNext = TempNode;
CurNode = TempNode;
}
}
return head;
}
void printList(ListNode* head)
{
while (head)
{
if (head->pNext)
cout<<head->mVlaue<<"->";
else
cout<<head->mVlaue;
head= head->pNext;
}
cout<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
ListNode* head = NULL;
head = creatList();
printList(head);
ListNode* NewHead = reverseList(head);
printList(NewHead);
system("pause");
return 0;
}