206リバースリンクリスト*

206リバースリンクリスト*

https://leetcode.com/problems/reverse-linked-list/

タイトル説明

単独リンクリストを逆にします。

例:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

ファローアップ:

リンクリストは、いずれかの繰り返しや再帰的に反転させることができます。あなたは両方を実装してもらえますか?

C ++の実装1

リストをフリップ非常に古典的な問題であり、反復的なアプローチは、心に必要。

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (!head) return nullptr;
        ListNode *prev = nullptr;
        while (head) {
            auto tmp = head->next;
            head->next = prev;
            prev = head;
            head = tmp;
        }
        return prev;
    }
};

C ++での2

再帰的な方法。

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (!head || !head->next) return head;
        auto tmp = head->next;
        auto new_head = reverseList(head->next);
        tmp->next = head;
        head->next = nullptr;
        return new_head;
    }
};
公開された455元の記事 ウォンの賞賛8 ビュー20000 +

おすすめ

転載: blog.csdn.net/Eric_1993/article/details/104897083