Skip to content

Instantly share code, notes, and snippets.

@wataruoguchi
Last active July 29, 2019 06:10
Show Gist options
  • Save wataruoguchi/a1182469b8c796fbacdcd2c3eab981f8 to your computer and use it in GitHub Desktop.
Save wataruoguchi/a1182469b8c796fbacdcd2c3eab981f8 to your computer and use it in GitHub Desktop.
Given a sorted circularly linked list of Nodes that store integers and a new Node, Insert the new Node into the correct position. (Duplicates allowed)
// Given a sorted circularly linked list of Nodes that store integers and a new Node, Insert the new Node into the correct position. (Duplicates allowed)
class Node {
constructor(val, next) {
this.val = val;
this.next = next;
}
}
function printList(head) {
let tmp = head;
let arr = [];
let idx;
for (idx = 0; idx < 16; idx++) {
if (tmp) {
arr.push(tmp.val);
tmp = tmp.next;
} else {
break;
}
}
return arr;
}
function addInt(head, num) {
let tmp = head;
let next = tmp.next;
while (tmp) {
if ((next.val < tmp.val) || (tmp.val < num && next.val >= num)) {
// When it's smallest, or biggest
tmp.next = new Node(num, tmp.next);
break;
}
tmp = tmp.next;
next = tmp.next;
}
}
const head = new Node(1, new Node(2,
new Node(4, new Node(4, new Node(5, new Node(6, new Node(7, new Node(8))))))));
// Circularly linked list
head.next.next.next.next.next.next.next.next = head;
// Make sure it's circular
console.log(printList(head).join(',') === '1,2,4,4,5,6,7,8,1,2,4,4,5,6,7,8');
addInt(head, 4);
console.log(printList(head).join(',') === '1,2,4,4,4,5,6,7,8,1,2,4,4,4,5,6');
addInt(head, 9);
addInt(head, 0);
addInt(head, 3);
console.log(printList(head).join(',') === '1,2,3,4,4,4,5,6,7,8,9,0,1,2,3,4');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment