Problem Solving/LeetCode

[LeetCode] C++ 24. Swap Nodes in Pairs

LeeJaeJun 2024. 8. 17. 01:06
728x90
반응형

https://leetcode.com/problems/swap-nodes-in-pairs/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* swapPairs(ListNode* head) {
        if (!head || !head->next) {
            return head;
        }

        ListNode* firstNode = head;
        ListNode* secondNode = head->next;

        firstNode->next = swapPairs(secondNode->next);
        secondNode->next = firstNode;

        return secondNode;
    }
};

 

풀이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* swapPairs(ListNode* head) {
        if (!head || !head->next) {
            return head;
        }

        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        ListNode* prev = dummy;

        while(head && head->next){
            ListNode* firstNode = head;
            ListNode* secondNode = head->next;

            prev->next = secondNode;
            firstNode->next = secondNode->next;
            secondNode->next = firstNode;

            prev = firstNode;
            head = firstNode->next;
        }

        return dummy->next;
    }
};

728x90
반응형