Here is the interview question prompt, presented for reference.
Write a recursive algorithm that swaps every two nodes in a linked list. This is often called a pairwise swap. For example:
/*
original list
1 -> 2 -> 3 -> 4
after swapping every 2 nodes
2 -> 1 -> 4 -> 3
*/
You may assume that the definition of a linked list
node is:
function Node(val) {
this.value = val;
this.next = null;
}
The method will be invoked as such after setup:
const list = new Node(1);
list.next = new Node(2);
list.next.next = new Node(3);
list.next.next.next = new Node(4);
swapEveryTwo(list);
100000
-1000000000
and 1000000000
O(n)
O(n)
Note: The strength of linked lists is that you can dynamically add or remove any nodes within a constant time, given the address of the node. This is not possible in arrays or a sequential memory holding data structure. Each node in a linked list is created dynamically on the heap section of the memory. For this reason, you can create a very large Linked List (most probably larger than an array of the same size) as long as you have a memory to allocate. Creating more nodes than your memory can store will result in a heap overflow.
You can see the full challenge with visuals at this link.
Challenges • Asked about 5 years ago by Denis G.
This is the main discussion thread generated for Swap Every Two Nodes In A Linked List.
function toArray(head) {
let res = [];
while(head) { res.push(head.val); head = head.next; }
return res;
}
function toList(arr) {
if(arr.length == 0) return null;
const head = new Node(arr[0]);
for(let i=1, cur = head ; i
Thanks, but there is a small mistake that the definition of the value of Node is value not val .
No Test Cases?? Just Marking as Complete ??