定义的类:
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
#head = null;
#length = 0;
append(data) {//向链表结尾添加节点
let newnode = new Node(data);
if (this.#head == null) {
this.#head = newnode;
} else {
let current = this.#head;
while (current.next != null) {//循环找最后一个节点
current = current.next;
}
current.next = newnode;
}
this.#length++;
}
insert(position, data) {
// 越界判断(超出链表范围)
if (position < 0 || position > this.#length) return false;
let newnode = new Node(data);
if (position == 0) {//开始位置插入
newnode.next = this.#head;
this.#head = newnode;
}
// else if(position == this.#length){//结尾位置插入
// this.append(data);
// }
else {//中间插入(包含了结尾位置插入)
let previous = null;
let current = this.#head;
for (let i = 1; i <= position; i++) {//循环找到指定位置的节点
previous = current;
current = current.next;
}
previous.next = newnode;
newnode.next = current;
}
this.#length++;
return newnode;
}
indexOf(data) {
let current = this.#head;
for (let i = 0; i < this.#length; i++) {
if(current && current.data == data){
return i;//找到了就把下标索引返回
}
current = current.next;
}
return -1;//循环结束还没找到就返回-1
}
getNodeAt(position){
let current = this.#head;
for (let i = 1; i <= position; i++) {
current = current.next;
}
return current;
}
removeAt(position) {
// 越界判断(超出链表范围)
if (position < 0 || position >= this.#length) return null;
let current = this.#head;
let previous = current;
for (let i = 1; i <= position; i++) {
previous = current;
current = current.next;
}
previous.next = current.next;
if(position == 0){//要删除的是头结点
this.#head = this.#head.next;
}
this.#length--;
return current;
}
remove(data) {
let index = this.indexOf(data);
return this.removeAt(index);
}
update(position, data) {
let current = this.#head;
for (let i = 1; i <= position; i++) {
current = current.next;
}
current.data = data;
}
isEmpty() {
return this.#length === 0
}
size() {
return this.#length
}
toString() {
let str = '';
let current = this.#head;
for (let i = 0; i < this.#length; i++) {
str += ' ' + current.data;
current = current.next;
}
return str;
}
}
js代码:
function Game(num,...res){//...res代表最后剩余的所有参数
let linkelist = new LinkedList();
res.forEach(item=>{
linkelist.append(item);
})
let count = 0;
while(linkelist.size() > 1){
count++;
if(count == num){//当count计数到与num相同时,进入if语句,被淘汰,并且count清空,重新计数
console.log(linkelist.removeAt(0).data + '被淘汰了');
count = 0;
}else{//count没有计数到num时,就从头部移除,移入到尾部
linkelist.append(linkelist.removeAt(0).data);
}
}
return linkelist.removeAt(0).data + '胜利了';//剩余最后一个,跳出while循环
}
console.log(Game(7,'Jack','John','Carl','Tom','Ingrid'));