Given a linked list, swap every two adjacent nodes and return its head.
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 {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *current = head, *prev = nullptr;
while (current != nullptr && current->next != nullptr) {
ListNode *next = current->next;
if (current == head) head = next;
current->next = next->next;
next->next = current;
if (prev != nullptr) prev->next = next;
prev = current;
current = current->next;
}
return head;
}
};