Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import LinkedListNode from './linked-list-node.js';
- export default class DoublyLinkedList {
- #head = null;
- #tail = null;
- #count = 0;
- constructor(){
- this.#head=null;
- this.#tail=null;
- this.#count=0;
- }
- get count() {
- return this.#count;
- }
- get head() {
- return this.#head;
- }
- get tail() {
- return this.#tail;
- }
- get isEmpty() {
- return !this.#head;
- }
- addFirst(value) {
- const node = new LinkedListNode(value);
- if (this.isEmpty) {
- this.#head = node;
- this.#tail = this.#head;
- } else {
- node.next = this.#head;
- this.#head = node;
- }
- this.#count = this.#count + 1;
- }
- addLast(value) {
- const node = new LinkedListNode(value);
- if (this.isEmpty) {
- this.#head = node;
- this.#tail = node;
- } else {
- this.#tail.next = node;
- this.#tail = this.#tail.next;
- }
- this.#count = this.#count + 1;
- }
- removeFirst() {
- if (this.isEmpty){
- throw new Error('node empty');
- }
- const value = this.#head.value;
- this.#head = this.#head.next;
- this.#count--;
- return value;
- }
- removeLast() {
- if (this.isEmpty){
- throw new Error('node empty');
- }
- const value = this.#tail.value;
- this.#tail = this.#tail.prev;
- this.#count--;
- return value;
- }
- insertBefore(node, value) {
- this.#count++;
- const newNode = new LinkedListNode(value);
- if (node.value === this.#head.value) {
- this.#head.prev = newNode;
- newNode.next = this.#head;
- this.#head = newNode;
- }
- newNode.prev = node.prev;
- node.prev.next = newNode;
- newNode.next = node;
- }
- insertAfter(node, value) {
- if(node === null){
- throw new Error('the given node cannot be null');
- }
- const newNode = new LinkedListNode(value);
- newNode.next = node.next;
- node.next = newNode;
- if(node === this.#tail){
- this.#tail.next = newNode;
- this.#tail=this.#tail.next;
- }
- this.#count++;
- }
- find(val) {
- let current = this.#head;
- let final = null;
- while(current){
- if(current.value === val) {
- final = current;
- }
- current =current.next;
- }
- return final;
- }
- values(){
- if(this.isEmpty){
- return [];
- }
- let current = this.#head;
- let final = [];
- while(current){
- final.push(current.value);
- current = current.next;
- }
- return final;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment