class CList {
constructor() {
this.head = null;
this.length = 0;
}
append(element) {
let newNode = new Node(element);
if (this.head == null) {
this.head = newNode;
newNode.next = this.head;
} else {
let current = this.head;
// 1
// 2
while (current.next != this.head) {
current = current.next;
}
newNode.next = this.head;
current.next = newNode;
}
this.length++
return true;
}
insert(position, element) {
// 越界判断
if (position < 0 || position > this.length) {
return false;
}
let newNode = new Node(element)
let current = this.head;
if (position == 0) {
// 找到最后一个节点
while (current.next != this.head) {
current = current.next;
}
newNode.next = this.head;
current.next = newNode;
this.head = newNode;
} else if (position == this.length) {
while (current.next != this.head) {
current = current.next;
}
newNode.next = this.head;
current.next = newNode;
} else {
let index = 0;
while (index++ != position - 1) {
current = current.next;
}
newNode.next = current.next;
current.next = newNode;
}
this.length++;
return true;
}
removeAt(position) {
// 越界判断
if (position < 0 || position >= this.length) {
return false;
}
let current = this.head;
if (position == 0) {
while (current.next != this.head) {
current = current.next;
}
current.next = this.head.next;
this.head = this.head.next;
} else if (position == this.length - 1) {
while (current.next.next != this.head) {
current = current.next;
}
current.next = this.head;
} else {
let index = 0;
while (index++ != position - 1) {
current = current.next;
}
current.next = current.next.next;
}
this.length--;
return true;
}
indexOf(element) {
if (this.head.data == element) {
return 0;
}
let current = this.head.next;
let index = 1;
while (current != this.head) {
if (current.data == element) {
return index;
}
index++;
current = current.next;
}
return -1;
}
remove(element) {
return this.removeAt(this.indexOf(element));
}
}