Coder's Cat

LeetCode: Swap Nodes in Pairs

2019-12-31

Solution for LeetCode LeetCode: Swap nodes in Pairs

Leetcode Problem: Swap Nodes in Pairs

https://leetcode.com/problems/swap-nodes-in-pairs/

Given a linked list, swap every two adjacent nodes and return its head.

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.

Explanation and solution

To solve this question, you need to master basic operation skills for link list, and how to swap two nodes.

The time complexity is $O(N)$.

Use a dummy node will simplify the operations.

file:img/2019_12_31_leetcode-swap-nodes-in-pairs.org_20191231_123305.png

The result is:

file:img/2019_12_31_leetcode-swap-nodes-in-pairs.org_20191231_122118.png

class Solution  {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* cur = head;
ListNode* pre = dummy;
while(cur && cur->next) {
ListNode* t = cur->next->next;
pre->next = cur->next;
cur->next->next = cur;
cur->next = t;
pre = cur;
cur = t;
}
return dummy->next;
}
};

Recursive solution

The code will be cleaner if we use recursive strategy, but it will be slower in time performance.

file:img/2019_12_31_leetcode-swap-nodes-in-pairs.org_20191231_123450.png

class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head == NULL)
return NULL;
if(head->next == NULL)
return head;

ListNode* next = head->next;
head->next = swapPairs(next->next);
next->next = head;

return next;
}
};

Join my Email List for more insights, It's Free!😋