LeetCode HOT100 - 反转链表

核心点就是不要真想着反转所以考虑从末尾开始怎么去做

就是走一步反转一步

因为链表只能记录当前相邻的节点,所以从头节点开始逐个改变它们的 next

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *pre = nullptr, *cur = head;
        while (cur) {
            auto nxt = cur->next;
            cur->next = pre;
            pre = cur;
            cur = nxt;
        }
        return pre;
    }
};
posted @ 2026-03-18 17:18  rdcamelot  阅读(2)  评论(0)    收藏  举报