Given a linked list, swap every two adjacent nodes and return its head.
Your algorithm should use only constant space. You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Solution:
/**
* 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 == nullptr)
return head;
ListNode dummy{-1, head};
ListNode* p = &dummy;
ListNode* prev = p->next;
ListNode* cur = prev->next;
while(prev && cur)
{
prev->next = cur->next;
cur->next = prev;
p->next = cur;
p = prev;
prev = prev->next;
cur = prev ? prev->next : nullptr;
}
return dummy.next;
}
};