反转链表:遍历链表的同时进行反转,只要我们将每个节点的next指针指向前一个节点,遍历完毕就反转完毕。在改变指针指向节点时我们需要记录前一个节点temp。
遍历链表时,先找到当前节点的下一个节点node,然后将当前的节点cur的next指针指向temp,最后向前遍历,把当前节点赋给temp,下一个节点node赋给cur,直到当前节点cur为空,此时说明已经遍历完尾节点,返回temp即为反转后的头节点。
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead==nullptr)
return nullptr;
ListNode* temp=nullptr;
ListNode* cur=pHead;
ListNode* node=nullptr;
while(cur!=nullptr)
{
node=cur->next;
cur->next=temp;
temp=cur;
cur=node;
}
return temp;
}
};