题目描述
输入一个链表,反转链表后,输出链表的所有元素。
需要借用3个临时变量,注意边界
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead==NULL||pHead->next==NULL)
return pHead;
ListNode* pre=pHead;
ListNode* cur=pHead->next;
ListNode* next=cur->next;
pHead->next=NULL;
while(next!=NULL)
{
cur->next=pre;
pre=cur;
cur=next;
next=next->next;
}
cur->next=pre;
return cur;
}
};