#include <iostream>
using namespace std;
/*****************************************************************************
NC78
题目描述:
输入一个链表,反转链表后,输出新链表的表头。
示例1
输入:{1,2,3}
返回值:{3,2,1}
*****************************************************************************/
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
ListNode* ReverseList(ListNode* pHead) {
if (pHead == NULL || pHead->next == NULL)
{
return pHead;
}
ListNode *p = pHead;
ListNode *q = pHead->next;
//1(pHead,p),2(q),3,4,5,6,7,8,9
//1(pHead),2(p),3(q),4,5,6,7,8,9
//1,2,3,4,5,6,7,8(p),9(pHead,q)
pHead->next = NULL;
while (q->next != NULL)
{
ListNode *temp_q = q->next;
q->next = p;
p = q;
q = temp_q;
}
q->next = p;
return q;
}
int main()
{
ListNode a(1);
ListNode b(2);
ListNode c(3);
ListNode d(4);
ListNode e(5);
a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;
ReverseList(&a);
return 0;
system("pause");
}