Swap Adjacent Linked List Nodes
Updated
Problem statement
You are given head, the first node of a singly linked list. Swap the nodes in adjacent pairs: the 1st node with the 2nd, the 3rd with the 4th, and so on. If the list has an odd number of nodes, the last node has no partner and stays at the end.
Do the swaps by changing the next pointers, not by changing the values stored in the nodes. Return the head of the new list, or null if the list is empty.
The returned list is shown as an array of its values, with [] for an empty list. The judge can only check this order of values, so relinking the nodes is a rule for you to follow rather than something the tests can see.
Function
swapInPairs(head: ListNode) → ListNodeExamples
Example 1
head = [10,20,30,40,50,60]return = [20,10,40,30,60,50]The pairs are (10, 20), (30, 40) and (50, 60). The two nodes of each pair trade places, giving 20 -> 10 -> 40 -> 30 -> 60 -> 50. The new head is the node that holds 20.
Example 2
head = [7,3,9,1,5]return = [3,7,1,9,5]The pairs are (7, 3) and (9, 1), which become 3 -> 7 and 1 -> 9. The fifth node, 5, has no partner, so it stays last: 3 -> 7 -> 1 -> 9 -> 5.
Example 3
head = [-4]return = [-4]There is only one node, so there is no pair to swap. The list is returned as it is.
Constraints
- The number of nodes in the list is between
0and1000. -10^5 <= Node.val <= 10^5
More Nutanix Phone Screen questions
- Top K Most Frequent ValuesPHONE SCREEN · Seen Mar 2025
- Unique Triplets Summing to ZeroPHONE SCREEN · Seen Sep 2024
- Find the Duplicate in a Read-Only ArrayPHONE SCREEN · Seen Apr 2021
- Kth Largest Element in an ArrayPHONE SCREEN · Seen Feb 2020
- Kth Smallest Element in a BSTPHONE SCREEN · Seen Feb 2020
- Outline of a Binary TreePHONE SCREEN · Seen Jan 2020
- Print All File and Folder PathsPHONE SCREEN · Seen Dec 2019
- Inorder Predecessor in a BSTPHONE SCREEN · Seen Jan 2019
- K Largest and K Smallest ValuesPHONE SCREEN · Seen Jan 2019
- Odd Numbers Up and BackPHONE SCREEN · Seen Jan 2019
Similar questions at other companies
- Flatten a Multilevel Doubly Linked ListBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Sort a Linked ListAdobe · PHONE SCREENAdobe interview questions
- Reverse a Linked ListCisco · PHONE SCREENCisco interview questions
- Reverse a Linked ListApple · PHONE SCREENApple interview questions
- Reverse a Singly Linked ListChubb · PHONE SCREENChubb interview questions
- Merge K Sorted Linked ListsBharatPe · PHONE SCREEN
- Reverse Nodes in K-GroupByteDance · PHONE SCREENByteDance interview questions
- Reverse a Singly Linked ListExpedia · PHONE SCREEN · ONSITE INTERVIEWExpedia interview questions
- Reverse a Singly Linked ListSuperhuman · PHONE SCREENSuperhuman interview questions
- Sorted Doubly Linked List to Balanced BST In PlaceSalesforce · ONSITE INTERVIEWSalesforce interview questions