Skip to content

Commit

Permalink
Solve: Swap Nodes in Pairs
Browse files Browse the repository at this point in the history
  • Loading branch information
fkdl0048 committed Oct 4, 2024
1 parent 0c086d8 commit 3433adc
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions LeetCode/Swap Nodes in Pairs.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* 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) {
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* current = dummy;

while(current->next != nullptr && current->next->next != nullptr){
ListNode* first = current->next;
ListNode* second = current->next->next;

first->next = second->next;
second->next = first;
current->next = second;

current = first;
}

return dummy->next;
}
};

0 comments on commit 3433adc

Please sign in to comment.