> 文章列表 > 使用js封装一个循环链表

使用js封装一个循环链表

使用js封装一个循环链表

直接不说废话,直接上代码,这里继承了单向链表的类LinkList ,可以查看之前的文章,点这里

class Node {constructor(element) {this.element = element;this.next = null;}
}class CirularLinkedList extends LinkList {constructor() {super();}push(element) {const node = new Node(element);let current;if (this.head === null) {this.head = node;} else {current = this.getNodeAt(this.size() - 1);console.log(current);current.next = node;node.next = this.head;}node.next = this.head;this.count++;}insert(element, index) {if (index >= 0 && index <= this.count) {const node = new Node(element);let current = this.head;if (index === 0) {if (this.head === null) {this.head = node;node.next = this.head;} else {node.next = current;current = this.getNodeAt(this.size() - 1);this.head = node;console.log(current);current.next = this.head;}} else {const previous = this.getNodeAt(index - 1);node.next = previous.next;previous.next = node;}this.count++;return true}return false}removeAt(index) {if (index >= 0 && index < this.count) {let current = this.head;if (index === 0) {if (this.size() === 0) {this.head = undefined;} else {let last = this.getNodeAt(this.size() - 1);this.head = this.head.next;}} else {const previous = thsi.getNodeAt(index - 1);current = previous.next;previous.next = current;}}}
}