Problem Solving/LeetCode

[LeetCode] C++ 206. Reverse Linked List

LeeJaeJun 2024. 8. 16. 23:26
728x90
반응형

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

 

문제

 

문제 분석

- 재귀를 이용해서, 또는 반복문을 이용해서 풀 수 있습니다.

 

풀이 1 (재귀)

/**
 * 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) {
        if (head == nullptr || head->next == nullptr) {
            return head;
        }

        ListNode* newHead = reverseList(head->next);

        head->next->next = head;
        head->next = nullptr;

        return newHead;
    }
};

/**
 * 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 {
private:
    ListNode* reverse(ListNode* curr, ListNode* prev){
        if(curr == nullptr){
            return prev;
        }

        ListNode* next = curr->next;
        curr->next = prev;

        return reverse(next, curr);
    }
public:
    ListNode* reverseList(ListNode* head) {
        return reverse(head, nullptr);
    }
};

풀이2 (반복문)

/**
 * 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* prev = nullptr;
        ListNode* curr = head;

        if(head == nullptr){
            return curr;
        }

        while(curr){
            ListNode* nextNode = curr->next;
            curr->next = prev;
            prev = curr;
            curr = nextNode;
        }

        return prev;
    }
};

728x90
반응형