描述:
输入一个链表,反转这个链表,并输出反转后链表的头指针;
注:本核心代码都是在牛客网在线编程中进行测试通过,并且在VS2015上进行编译通过;
代码如下所示:
#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) {
if (pHead == NULL) return NULL;
ListNode* preNode = NULL;
ListNode* Node = pHead;
ListNode* ReverseNode = NULL;
while (Node!=NULL) {
ListNode* PNext = Node->next;
if (PNext == NULL)
ReverseNode = Node;
Node->next = preNode;
preNode = Node;
Node = PNext;
}
return ReverseNode;
}
};
int main(int argc,char** argv) {
Solution test_;
ListNode test(12);
ListNode test1(88);
ListNode test12(192);
ListNode test13(162);
ListNode test14(1142);
test.next = &test1;
test1.next = &test12;
test12.next = &test13;
test13.next = &test14;
ListNode* NewHead = test_.ReverseList(&test);
while (NewHead!=NULL)
{
cout << (*NewHead).val << endl;
NewHead = NewHead->next;
}
system("pause");
return 0;
}
结果如下所示: