94 lines
2.6 KiB
JavaScript
94 lines
2.6 KiB
JavaScript
const readline = require("readline");
|
||
const rl = readline.createInterface(process.stdin, process.stdout);
|
||
|
||
class Node {
|
||
previous;
|
||
value;
|
||
next;
|
||
}
|
||
|
||
class LinkList {
|
||
head;
|
||
length;
|
||
constructor(length) {
|
||
// 还是需要头结点,此时head表示其中第0个结点,length必须大于0
|
||
this.length = length;
|
||
this.head = new Node();
|
||
// this.head.value = 1;
|
||
let current, previous = this.head;
|
||
for (let i = 1; i <= this.length; i++) {
|
||
current = new Node();
|
||
current.value = i;
|
||
previous.next = current;
|
||
current.previous = previous;
|
||
previous = current;
|
||
}
|
||
current.next = this.head.next;
|
||
this.head.next.previous = current;
|
||
// this.head.next = this.current; // 不能多重赋值,赋值语句会返回undefined
|
||
this.head.previous = current;
|
||
}
|
||
remove(node) {
|
||
node.previous.next = node.next;
|
||
node.next.previous = node.previous;
|
||
// delete node; // JavaScript里应该无法直接删除
|
||
this.length--;
|
||
return true;
|
||
}
|
||
|
||
// 找到从当前结点开始第n个结点(可以为负数),当前结点是第0个
|
||
// 并且再向后返回一个结点
|
||
get_n_after_node(node, n) {
|
||
let property_name = "next";
|
||
if (n < 0) {
|
||
property_name = "previous";
|
||
n = -n;
|
||
}
|
||
if (this.length < 3) return false;
|
||
for (let i = 0; i < n; i++) { // 向后走n个,例如从0开始,到3结束
|
||
node = node[property_name];
|
||
}
|
||
return node;
|
||
}
|
||
}
|
||
|
||
function main(people_num, num1) {
|
||
let link_list = new LinkList(people_num);
|
||
let current = link_list.head;
|
||
let temp;
|
||
while (true) {
|
||
temp = link_list.get_n_after_node(current, num1);
|
||
if (!temp) break;
|
||
current = temp;
|
||
link_list.remove(current);
|
||
}
|
||
// 此时current是最后一个被删掉的结点,它的next和previous都是存在的结点
|
||
current = current.next;
|
||
link_list.head.next = current;
|
||
for (let i = 0; i < link_list.length; i++) {
|
||
console.log(current.value);
|
||
current = current.next;
|
||
}
|
||
}
|
||
|
||
function input(prompt) {
|
||
return new Promise((resolve) => {
|
||
rl.question(prompt, (answer) => {
|
||
resolve(answer);
|
||
});
|
||
});
|
||
}
|
||
|
||
async function main_() {
|
||
people_num = parseInt(await input("输入人数"));
|
||
num1 = parseInt(await input("输入第一个数字"));
|
||
main(people_num, num1);
|
||
rl.close();
|
||
}
|
||
|
||
main_()
|
||
|
||
// 输入人数41
|
||
// 输入第一个数字3
|
||
// 16
|
||
// 31
|