LeetCode - 翻转链表

https://leetcode.cn/problems/fan-zhuan-lian-biao-lcof/

递归法

    ListNode* reverseList(ListNode* head) {
        if (head == nullptr || head->next == nullptr)
            return head;

        auto ret = reverseList(head->next);
        head->next->next = head;
        head->next = nullptr;

        return ret;
    }

迭代法

    ListNode* reverseList(ListNode* head) {
        if (head == nullptr || head->next == nullptr)
            return head;

        ListNode dummy{-1};
        dummy.next = head;
        while(head->next)
        {
            ListNode* tmp = head->next->next;
            head->next->next = dummy.next;
            dummy.next = head->next;
            head->next = tmp;
        }

        return dummy.next;
    }

你可能感兴趣的:(leetcode,链表,leetcode,算法)