力扣 206. 反转链表

66 阅读1分钟

为了防止找不到下一个元素,需要额外的指针

时间复杂度 O(n)O(n), 空间复杂度 O(1)O(1)

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head == nullptr or head -> next == nullptr) return head;
        ListNode *pre = head, *now = pre -> next, *suf = now -> next;
        pre -> next = nullptr;
        while(now != nullptr) {
            now -> next = pre;
            pre = now;
            now = suf;
            if(suf != nullptr) suf = suf -> next;
        }
        return pre;
    }
};