LeetCode 24: Swap Nodes in Pairs Solution

Master LeetCode problem 24 (Swap Nodes in Pairs), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

24. Swap Nodes in Pairs

Problem Explanation

Explanation:

To solve this problem, we can use a dummy node to help with handling edge cases. We will iterate through the linked list, swapping pairs of adjacent nodes.

  1. Create a dummy node and point it to the head of the linked list.
  2. Iterate through the linked list by pairs, swapping the nodes.
  3. Update the pointers accordingly.
  4. Return the new head of the linked list after swapping.

Time Complexity: O(N) where N is the number of nodes in the linked list. Space Complexity: O(1)

Solution Code

class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode current = dummy;

        while (current.next != null && current.next.next != null) {
            ListNode first = current.next;
            ListNode second = current.next.next;
            first.next = second.next;
            current.next = second;
            current.next.next = first;
            current = current.next.next;
        }

        return dummy.next;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 24 (Swap Nodes in Pairs)?

This page provides optimized solutions for LeetCode problem 24 (Swap Nodes in Pairs) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 24 (Swap Nodes in Pairs)?

The time complexity for LeetCode 24 (Swap Nodes in Pairs) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 24 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 24 in Java, C++, or Python.

Back to LeetCode Solutions