Woodstock Blog

a tech blog for general algorithmic interview questions

[LeetCode 24] Swap Nodes in Pairs

Question

link

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

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

Stats

Frequency 4
Diffficulty 2
Adjusted Difficulty 3
Time to use ----------

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

Solution

The easier solution is of course recursion. We only need to swap 2 nodes and then call the method recursively. Find code below.

However, there exists iterative solution, just slightly complex. Read here for more. Two pieces of iterative code are posted below.

My code

Recursion

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode temp = head.next;
        head.next = swapPairs(temp.next);
        temp.next = head;
        return temp;
    }
}

Iterative solution using while loop. ref

public ListNode swapPairs(ListNode head) {
    if (head == null) return head;
    ListNode preHead = new ListNode(1);
    preHead.next = head;
    ListNode cur = head, pre = preHead;
    while (cur != null && cur.next != null) {
        pre.next = cur.next;
        ListNode newCur = cur.next.next;
        cur.next.next = cur;
        cur.next = newCur;
        pre = cur;
        cur = newCur;
    }
    return preHead.next;
}

Iterative solution using for loop. ref

public ListNode swapPairs(ListNode head) {
    ListNode start = new ListNode(0);
    start.next = head;
    for (ListNode cur = start; cur.next != null 
           && cur.next.next != null; cur = cur.next.next) {
        cur.next = swap(cur.next, cur.next.next);
    }
    return start.next;
}

private ListNode swap(ListNode next1, ListNode next2) {
    next1.next = next2.next;
    next2.next = next1;
    return next2;
}