反转链表
输入一个链表,反转链表后,输出新链表的表头。
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == nullptr)
return nullptr; //pHead 为当前节点,如果当前节点为空的话,那就什么也不做,直接返回null;
ListNode* pre = nullptr; //需要pre和next的目的是让当前节点从pre->pHead->next1->next2变成pre<-head next1->next2;
ListNode* next = nullptr;//即pre让节点可以反转所指方向,但反转之后如果不用next节点保存next1节点的话,此单链表就此断开了
while(pHead != nullptr){
next = pHead->next; //先将pHead的next存起来
pHead->next = pre; //然后将pHead从指向next指向pre
pre = pHead; //head指向pre后,就继续依次移动下一个节点,继续下一次的指针反转
pHead = next;
}
return pre;
}
};
链表的知识要好好复习下了。