SharedSchoolSpace/作业/数据结构-金健/JavaScript/第二章作业2.js

135 lines
3.6 KiB
JavaScript
Raw Normal View History

2023-10-26 14:24:53 +08:00
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, num2) {
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);
temp = link_list.get_n_after_node(current, num2);
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);
});
});
}
function visualize(dryrun, link_list) {
if (dryrun) {
return;
}
let result = {
"kind": { "graph": true },
"nodes": [
],
"edges": [
]
};
let current = link_list.head.next;
for (let i = 0; i < link_list.length; i++) {
result.nodes.push({
"id": String(i),
"label": String(current.value)
});
current = current.next;
result.edges.push({
"from": String(i),
"to": String(i + 1)
});
}
result.edges[result.edges.length - 1].to = "0";
return result;
}
async function main_() {
visualize(true); // 不加这行可能它转化成Promise的时候不会放到闭包作用域里。
people_num = parseInt(await input("输入人数"));
num1 = parseInt(await input("输入第一个数字"));
num2 = parseInt(await input("输入第二个数字"));
main(people_num, num1, num2);
rl.close();
}
main_()
// 输入人数10000
// 输入第一个数字123
// 输入第二个数字-654
// 1299
// 4114
// 输入人数99999
// 输入第一个数字-848
// 输入第二个数字-351
// 80178
// 23680