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
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
[LeetCode] C++ 92. Reverse Linked List II (0) | 2024.08.17 |
---|---|
[LeetCode] C++ 328. Odd Even Linked List (0) | 2024.08.17 |
[LeetCode] C++ 2. Add Two Numbers (0) | 2024.08.17 |
[LeetCode] C++ 206. Reverse Linked List (0) | 2024.08.16 |
[LeetCode] C++ 21. Merge Two Sorted Lists (0) | 2024.08.16 |