연결리스트를 입력받아 페어단위로 스왑하라.
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Input: head = []
Output: []
Input: head = [1]
Output: [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 {
private:
int count;
int temp;
public:
Solution()
{
count = 0;
temp = 0;
}
ListNode* swapPairs(ListNode* head) {
if (head == NULL) return head;
else
{
if (count % 2 == 0)
{
temp = head->val;
if(head->next != NULL) head->val = head->next->val;
count++;
swapPairs(head->next);
}
else
{
head->val = temp;
count++;
swapPairs(head->next);
}
}
return head;
}
};
Runtime 0 ms / Memory 7.6 MB
https://leetcode.com/problems/swap-nodes-in-pairs/submissions/925082657/