24 Swap Nodes in Pairs

1. Question

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

For example, Given1->2->3->4, you should return the list as2->1->4->3.

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

2. Implementation

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode curNode = dummy;
        ListNode first = null, second = null;

        while (curNode.next != null && curNode.next.next != null) {
            first = curNode.next;
            second = curNode.next.next;
            first.next = second.next;
            second.next = curNode.next;
            curNode.next = second;
            curNode = first;
        }
        return dummy.next;
    }
}

3. Time & Space Complexity

时间复杂度O(n), 空间复杂度O(1)

Last updated

Was this helpful?