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

Naive solution: Traversal link list and reverse it on fly

Use a dummy node will simplify the operations.

2019_12_31_leetcode-swap-nodes-in-pairs.org_20191231_123305.png

The result is:

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.

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;
  }
};
Last Updated on

Leave a Reply

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