Advertisement
Guest User

Untitled

a guest
May 24th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Node {
  2.   constructor(data, prev = null, next = null) {
  3.     this.value = data;
  4.     this.prev = prev;
  5.     this.next = next;
  6.   }
  7. }
  8.  
  9. class linkList {
  10.   constructor() {
  11.     this.head = null;
  12.     this.tail = null;
  13.     this.size = 0;
  14.   }
  15.   addFront(data) {
  16.     let newFront = new Node(data, null, this.head);
  17.     if (!this.tail) this.tail = newFront;
  18.     if (this.head) this.head.prev = newFront;
  19.     this.head = newFront;
  20.     this.size++;
  21.   }
  22.  
  23.   addBack(data) {
  24.     let newBack = new Node(data, this.tail, null);
  25.     if (!this.head) this.head = newBack;
  26.     if (this.tail) this.tail.next = newBack;
  27.     this.tail = newBack;
  28.     this.size++;
  29.   }
  30.   popFront() {
  31.     if (this.size === 0) throw new Error("No data");
  32.     this.head = this.head.next;
  33.     this.head.prev = null;
  34.     this.size--;
  35.   }
  36.   popBack() {
  37.     if (this.size === 0) throw new Error("No data");
  38.     this.tail = this.tail.prev;
  39.     this.tail.next = null;
  40.     this.size--;
  41.   }
  42.   addAtIndex(index, data) {
  43.     let i = 0;
  44.     let newNode = new Node(data);
  45.     let tracer = this.head;
  46.     while (i < index) {
  47.       tracer = tracer.next;
  48.       i++;
  49.     }
  50.     tracer.next.pre = newNode;
  51.     tracer.next = newNode;
  52.     newNode.next = tracer.next;
  53.     newNode.pre = tracer;
  54.     this.size++;
  55.   }
  56.   popAtIndex(index) {
  57.     let i = 0;
  58.     let tracer = this.head;
  59.     while (i < index) {
  60.       tracer = tracer.next;
  61.       i++;
  62.     }
  63.     tracer.prev.next = tracer.next;
  64.     tracer.next.pre = tracer.pre;
  65.     this.size--;
  66.   }
  67. }
  68.  
  69. let aList = new linkList();
  70. aList.addFront(1);
  71. const alphabet = "a".split("");
  72. for (let i of alphabet) {
  73.   aList.addBack(i);
  74. }
  75. console.log(aList);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement