이중 연결 목록
17453 단어 javascript
class Node {
constructor(data, next = null, previous = null) {
this.data = data;
this.next = next;
this.previous = previous;
}
}
class linkedList {
constructor(head = null, tail = null) {
this.head = head;
this.tail = tail;
this.size = 0;
}
appendAtlast(data) {
let node = new Node(data);
if (this.head === null) {
this.head = node;
this.tail = node;
} else {
this.tail.next = node;
node.previous = this.tail;
this.tail = node;
}
this.size++;
}
addAtFirst(data) {
let node = new Node(data);
if (this.head === null) {
this.head = node;
} else {
this.head.previous = node;
node.next = this.head;
this.head = node;
}
this.size++;
}
addAtIndex(data, index) {
let node = new Node(data);
if (index === 0) {
this.addAtFirst(data);
return;
}
if (index >= this.size) {
return;
}
let count = 0;
let current;
while (count < index) {
current = current.next;
count++;
}
const previousNode = current.previous;
previousNode.next = node;
node.next = current;
node.previous = previousNode;
current.previous = node;
this.size++;
}
remove() {
if (this.tail) {
this.size--;
this.tail = this.tail.previous;
if (this.tail) {
this.tail.next = null;
} else {
this.head = null;
}
} else {
this.head = null;
}
}
removeAtIndex(index) {
if (!Number.isInteger(index) || index < 0 || index > this.sixe) {
console.log(`Invalid index. Current length is ${this.size}.`);
return this;
}
if (index === 0) {
this.head = this.head.next;
this.head.previous = null;
this.size--;
return;
}
if (index === this.size - 1) {
this.tail = this.tail.previous;
this.tail.next = null;
this.size--;
return;
}
let count = 0;
let current = this.head;
while (count < index) {
current = current.next;
count++;
}
const previousNode = current.previous;
const nextNode = current.next;
previousNode.next = nextNode;
nextNode.previous = previousNode;
this.size--;
}
print() {
let current = this.head;
console.log("Size", this.size);
while (current) {
console.log(` ${current.data}`);
current = current.next;
}
}
}
let ll = new linkedList();
ll.appendAtlast(100);
ll.appendAtlast(200);
ll.addAtFirst(99);
ll.appendAtlast(300);
ll.removeAtIndex(3);
ll.appendAtlast(300);
ll.remove();
ll.print();
Reference
이 문제에 관하여(이중 연결 목록), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/zeeshanali0704/doubly-linked-list-35gl텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)