牛客:BM1 反转链表
链接:反转链表_牛客题霸_牛客网
题解:
设置三个指针:pre记录前一个节点,cur记录当前节点,next记录后一个节点。遍历原链表,每次更新前保存next节点,cur->next更新为pre(反转链表),pre更新为当前节点cur,再继续更新下一个节点。
/*** struct ListNode {* int val;* struct ListNode *next;* ListNode(int x) : val(x), next(nullptr) {}* };*/
class Solution {
public:/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可** * @param head ListNode类 * @return ListNode类*/ListNode* ReverseList(ListNode* head) {// write code hereListNode* pre=nullptr;ListNode* cur=head;ListNode* next=nullptr;while(cur!=nullptr){next=cur->next;//保存下一个节点cur->next=pre;//反转链表pre=cur;//更新前一个结点cur=next;//更新当前节点}return pre;}
};