输入一个链表,反转链表后,输出新链表的表头。
1.使用三个指针,pPre指向当前结点的前一个结点,pNode指向当前结点,pNext指向当前结点的下一个结点。
2.先记录pNode的后一个结点pNext,让pNode指向pPre,移动pPre到pNode,移动pNode到pNext,直到pNode为空,此时pPre指向原链表的倒数第一个结点,也就是反转后新链表的头结点。
常规思路
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode* pPre=nullptr;
ListNode* pNode=pHead;
while(pNode)
{
ListNode* pNext=pNode->next;
pNode->next=pPre;
pPre=pNode;
pNode=pNext;
}
return pPre;
}
};
递归法
/*
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* last=ReverseList(pHead->next);
pHead->next->next=pHead;
pHead->next=NULL;
return last;
}
};