代码实现:
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode* pNewHead = pHead;
ListNode* pNodeNext = pHead->next;
ListNode* pNodePre = pHead;
if(pHead == NULL)
{
return NULL;
}
pNewHead->next = NULL;
while(1)
{
if(pNodeNext == NULL)
{
break;
}
pNodePre = pNewHead;
pNewHead = pNodeNext;
pNodeNext = pNodeNext->next;
pNewHead->next = pNodePre;
}
return pNewHead;
}
};
int main()
{
ListNode* head = NULL;
ListNode* temp = NULL;
ListNode* newNode = NULL;
int i = 0;
Solution s;
head = (ListNode*)malloc(sizeof(ListNode));
head->next = NULL;
head->val = 1;
temp = head;
for(i = 2; i < 6; i++)
{
newNode = (ListNode*)malloc(sizeof(ListNode));
newNode->next = NULL;
newNode->val = i;
temp->next = newNode;
temp = newNode;
}
temp = head;
while(temp)
{
cout << temp->val << " " ;
temp = temp->next;
}
cout << endl;
head = s.ReverseList(head);
temp = head;
while(temp)
{
cout << temp->val << " " ;
temp = temp->next;
}
cout << endl;
return 0;
}