Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { inheritLeadingComments } from '../../../../../../Library/Caches/typescript/4.9/node_modules/@babel/types/lib/index.js';
- import LinkedListNode from './linked-list-node.js';
- export default class DoublyLinkedList {
- #head =null
- #tail =null
- #count = 0
- addFirst(value) {
- const node = new LinkedListNode(value);
- if(!this.#head){
- this.#head=node;
- this.#tail = node;
- } else {
- node.next = this.#head;
- this.#head.prev = node;
- this.#head = node;
- }
- this.#count++;
- }
- addLast(value) {
- const node = new LinkedListNode(value);
- if(!this.#head) {
- this.#head = node;
- } else {
- this.#tail.next = node;
- node.prev = this.#tail;
- }
- this.#tail = node;
- this.#count++;
- }
- removeFirst(){
- if(!this.#head){
- throw new Error('No head');
- }
- if(this.count === 1){
- const val = this.#head.value;
- this.#head = null;
- this.#tail = null;
- this.#count--;
- return val;
- } else {
- const val = this.#head.value;
- this.#head = this.#head.next;
- this.#head.prev = null;
- this.#count--;
- return val;
- }
- }
- removeLast() {
- if(!this.#tail){
- throw new Error('No tail');
- }
- if(this.count === 1){
- const val = this.#tail.value;
- this.#head = null;
- this.#tail = null;
- this.#count--;
- return val;
- } else {
- const val = this.#tail.value;
- this.#tail.prev.next = null;
- this.#count--;
- return val;
- }
- }
- values() {
- let result = [];
- while(this.#head){
- result.push(this.#head.value);
- this.#head = this.#head.next;
- }
- return result;
- }
- insertAfter(node, val) {
- const newNode = new LinkedListNode(val);
- if(node === this.#tail){
- this.#tail.next = newNode;
- newNode.prev = this.#tail;
- this.#tail = newNode;
- this.#count++;
- } else {
- node.next.prev = newNode;
- newNode.prev = node;
- newNode.next = node.next;
- node.next = newNode;
- this.#count++;
- }
- }
- insertBefore(node,val){
- const newNode = new LinkedListNode(val);
- if(node === this.#head){
- newNode.next = this.#head;
- this.#head.prev = newNode;
- this.#head = newNode;
- this.#count++;
- } else {
- node.prev.next = newNode;
- newNode.next = node;
- node.prev = newNode;
- this.#count++;
- }
- }
- find(val) {
- let ref = this.#head;
- while(ref){
- if(ref.value === val) {
- return ref;
- }
- ref = ref.next;
- }
- return null;
- }
- valuesRev () { //gives the values in reverse order to check the validity of refrences.
- let result = [];
- while(this.#tail){
- result.push(this.#tail.value);
- this.#tail = this.#tail.prev;
- }
- return result;
- }
- get count() {
- return this.#count;
- }
- get head() {
- return this.#head;
- }
- get tail() {
- return this.#tail;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment