题解 | 反转链表
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { public: ListNode* ReverseList(ListNode* head){ ListNode* prev=nullptr;//初始前一个节点为nullptr ListNode*curr=head;//当前节点从表头开始 while(curr!=nullptr) {//遍历链表直到当前节点为nullptr ListNode* next=curr->next;//保存下一个节点 curr->next=prev;//反转当前节点的指向 prev=curr;//移动prev到当前节点 curr=next;//移动curr到下一个节点 } return prev;//遍历结束后,prev即为新表头 } };