> Uploading knowledge... _
[░░░░░░░░░░░░░░░░░░░░░░░░] 0%
blog logo
> CHICIO CODING_Pixels. Code. Unplugged.

Swap Nodes in Pairs

Leetcode Problem 24: Swap Nodes in Pairs

Problem Summary

Given the head of a linked list, swap every two adjacent nodes and return the new head. You must rearrange the nodes themselves — modifying node values is not allowed. If the list has an odd number of nodes, the last node is left in place.

Constraints:

  • The list has between 0 and 100 nodes.
  • Node values are non-negative integers up to 100.

Techniques

  • Linked List
  • Recursion

Solution

import { ListNode } from "../list-node"

function swapPairs(head: ListNode | null): ListNode | null {
    let dummy = new ListNode(-1, head)
    let current: ListNode | null = dummy

    while (current) {
        let first: ListNode | null = current.next ?? null
        let second: ListNode | null = first?.next ?? null
        let next: ListNode | null = second?.next ?? null

        if (first && second) {
            current.next = second
            second.next = first
            first.next = next
        }

        current = first
    }

    return dummy.next
}