LeetCode: Swap Nodes in Pairs


Leetcode Problem: 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.


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.


The result is:


class Solution  {
  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.


class Solution {
  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 *