
Leetcode Problem 24: Swap Nodes in Pairs
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:
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
}