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.
Input: head = [1,2,3,4] Output: [2,1,4,3]
1, 2 become 2, 1 and 3, 4 become 4, 3.
Input: head = [1,2,3] Output: [2,1,3]
3 has no partner, so it stays last.
0 to 100 nodes.0 <= node.val <= 100Lists are written as arrays here, like [1, 2, 3]. Your function works with ListNode objects, each with val and next.
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).
I'm here to help with #242 Swap Neighboring Tabs. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.