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.
class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode prev = null, current = head;
        int count = 1;
        while (current != null) {
            if (count == 2) {
                ListNode next = current.next;
                if (prev == null) {
                    current.next = head;
                    head.next = next;
                    prev = head;
                    head = current;
                } else {
                    current.next = prev.next;
                    prev.next.next = next;
                    prev.next = current;
                    prev = current.next;
                }
                current = next;
                count = 1;
                continue;
            }
            current = current.next;
            count++;
        }
        return head;
    }
}

Last updated