Skip to the code
cf.
+25 XP

#242 Swap Neighboring Tabs

medium

A browser extension has a "swap pairs" command for the tab strip: the 1st and 2nd tabs trade places, then the 3rd and 4th, and so on. A tab left without a partner at the end stays put. The tabs are a linked list.

Write swapPairs(head) that swaps every two neighboring nodes and returns the new head. Swap the nodes themselves by relinking; don't change any val.

Example 1

Input: head = [1,2,3,4]
Output: [2,1,4,3]

1, 2 become 2, 1 and 3, 4 become 4, 3.

Example 2

Input: head = [1,2,3]
Output: [2,1,3]

3 has no partner, so it stays last.

Constraints

  • The list has 0 to 100 nodes.
  • 0 <= node.val <= 100

Lists are written as arrays here, like [1, 2, 3]. Your function works with ListNode objects, each with val and next.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).