24. Swap Nodes in Pairs

24. Swap Nodes in Pairs

Description

Given alinked list, swap every two adjacent nodes and return its head. You must solve the problem withoutmodifying the values in the list’s nodes (i.e., only nodes themselves may be changed.)

Example 1:

1
2
3
Input: head = [1,2,3,4]

Output: [2,1,4,3]

Explanation:

Example 2:

1
2
3
Input: head = []

Output: []

Example 3:

1
2
3
Input: head = [1]

Output: [1]

Example 4:

1
2
3
Input: head = [1,2,3]

Output: [2,1,3]

Constraints:

  • The number of nodes in thelistis in the range [0, 100].
  • 0 <= Node.val <= 100

Hints/Notes

Solution

Language: C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* 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(0);
dummy.next = head;
ListNode* cur = &dummy;
while (cur->next && cur->next->next) {
ListNode* prev = cur;
ListNode* next1 = cur->next;
ListNode* next2 = cur->next->next;
ListNode* next = next2->next;
prev->next = next2;
next2->next = next1;
next1->next = next;
cur = next1;
}
return dummy.next;
}
};