24. Swap Nodes in Pairs

Description

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.)

 

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]

 

Constraints:

  • The number of nodes in the list is in the range [0, 100].

  • 0 <= Node.val <= 100

 

Thinking

That's right, a linked list problem. Swapping part of the nodes is a popular type of questions in linked list. All we need to do is to figure out what information we need to get before each transition/swapping. In this problem, to swap a pair of nodes, we need to know the node before the pair, the pointer of the pair of nodes, and the head of the following nodes. That is 4 pointers! Then we just need to cover all the edge cases: if you want to access a pointer's next node, make sure this pointer is not nullptr, or have some measurement to deal with it.

 

My approach

To initialize the *prev pointer, we need to have a dummy head that is prior to the *head, this makes our operation intuitive and convenient.

  • Edge case 1: Since I initialize *second as the first->next, I need to make sure first != nullptr.

  • Edge case 2: To prepare for the next round's second, if first is nullptr, it means the list has ended. Just assign nullptr to second to stop the loop and to avoid accessing nullptr.

 

What I learned

  1. Whenever you access the next pointer, thinking about if it is possible you access a nullptr.

  2. Using dummy node.

 

By bruce

Leave a Reply

Your email address will not be published. Required fields are marked *