用于存放学校的作业便于复习。
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

93 行
2.6 KiB

  1. const readline = require("readline");
  2. const rl = readline.createInterface(process.stdin, process.stdout);
  3. class Node {
  4. previous;
  5. value;
  6. next;
  7. }
  8. class LinkList {
  9. head;
  10. length;
  11. constructor(length) {
  12. // 还是需要头结点,此时head表示其中第0个结点,length必须大于0
  13. this.length = length;
  14. this.head = new Node();
  15. // this.head.value = 1;
  16. let current, previous = this.head;
  17. for (let i = 1; i <= this.length; i++) {
  18. current = new Node();
  19. current.value = i;
  20. previous.next = current;
  21. current.previous = previous;
  22. previous = current;
  23. }
  24. current.next = this.head.next;
  25. this.head.next.previous = current;
  26. // this.head.next = this.current; // 不能多重赋值,赋值语句会返回undefined
  27. this.head.previous = current;
  28. }
  29. remove(node) {
  30. node.previous.next = node.next;
  31. node.next.previous = node.previous;
  32. // delete node; // JavaScript里应该无法直接删除
  33. this.length--;
  34. return true;
  35. }
  36. // 找到从当前结点开始第n个结点(可以为负数),当前结点是第0个
  37. // 并且再向后返回一个结点
  38. get_n_after_node(node, n) {
  39. let property_name = "next";
  40. if (n < 0) {
  41. property_name = "previous";
  42. n = -n;
  43. }
  44. if (this.length < 3) return false;
  45. for (let i = 0; i < n; i++) { // 向后走n个,例如从0开始,到3结束
  46. node = node[property_name];
  47. }
  48. return node;
  49. }
  50. }
  51. function main(people_num, num1) {
  52. let link_list = new LinkList(people_num);
  53. let current = link_list.head;
  54. let temp;
  55. while (true) {
  56. temp = link_list.get_n_after_node(current, num1);
  57. if (!temp) break;
  58. current = temp;
  59. link_list.remove(current);
  60. }
  61. // 此时current是最后一个被删掉的结点,它的next和previous都是存在的结点
  62. current = current.next;
  63. link_list.head.next = current;
  64. for (let i = 0; i < link_list.length; i++) {
  65. console.log(current.value);
  66. current = current.next;
  67. }
  68. }
  69. function input(prompt) {
  70. return new Promise((resolve) => {
  71. rl.question(prompt, (answer) => {
  72. resolve(answer);
  73. });
  74. });
  75. }
  76. async function main_() {
  77. people_num = parseInt(await input("输入人数"));
  78. num1 = parseInt(await input("输入第一个数字"));
  79. main(people_num, num1);
  80. rl.close();
  81. }
  82. main_()
  83. // 输入人数41
  84. // 输入第一个数字3
  85. // 16
  86. // 31