Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

24. Swap Nodes in Pairs

Linked ListRecursion

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)

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;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.