Swap Nodes in Pairs

Posted by Bill on April 4, 2023

24. Swap Nodes in Pairs

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

1
2
3
4
5
6
7
8
9
10
11
12
13
Example 1:


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

Input: head = []
Output: []
Example 3:

Input: head = [1]
Output: [1]

C++ Solution

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
30
31
class Solution {
  public:
  ListNode *swapPairs(ListNode *head) {
    if (head == nullptr || head->next == nullptr) {
      return head;
    }
    ListNode *left = head;
    ListNode *right = head->next;
    ListNode *origin = right;
    ListNode *lastNode = nullptr;
    while (right != nullptr) {
      //1. swap right and left
      left->next = right->next;
      right->next = left;
      if (lastNode != nullptr) {
        lastNode->next = right;
      }
      lastNode = left;
      //2. set the new right and left
      left = left->next;
      if (left != nullptr) {
        right = left->next;
      } else {
        right = nullptr;
      }
    }
    return origin;
  }
};