题目描述
输入一个链表,反转链表后,输出新链表的表头。
解法
图示
代码:
/*
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;
if(pHead->next==NULL)
return pHead;
ListNode* temp1=pHead,*temp2=pHead->next;
ListNode* temp;
while(temp2)
{
if(temp1==pHead)
temp1->next=NULL;
temp=temp2;
temp2=temp2->next;
temp->next=temp1;
temp1=temp;
}
return temp;
}
};