Today I have solved the problem in javascript
Given a linked list, uniformly shuffle the nodes. What if we want to prioritize space over time?
const list = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))));
const shuffledList = shuffleLinkedList(list);
function ListNode(value, next = null) {
return { value, next };
}
function shuffleLinkedList(head) {
let current = head;
let count = 0;
while (current) {
count++;
current = current.next;
}
current = head;
for (let i = count - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
let nodeI = head;
for (let k = 0; k < i; k++) {
nodeI = nodeI.next;
}
let nodeJ = head;
for (let k = 0; k < j; k++) {
nodeJ = nodeJ.next;
}
const temp = nodeI.value;
nodeI.value = nodeJ.value;
nodeJ.value = temp;
current = current.next;
}
return head;
}
console.log(shuffledList);
Output:
{ value: 5, next: { value: 3, next: { value: 1, next: [Object] } } }
Comments
Post a Comment