堆和栈

Published: · LastMod: April 07, 2024 · 136 words

堆和栈 🔗

Queue 🔗

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import LinkedList from "./LinkedList";

class Queue {
  constructor() {
    this.linkedList = new LinkedList();
  }

  isEmpty() {
    return !this.linkedList.head;
  }

  peek() {
    if (this.isEmpty()) return null;
    return this.linkedList.head.value;
  }

  enqueue(value) {
    this.linkedList.prepend(value);
  }

  dequeue() {
    return this.linkedList.deleteHead();
  }
}

Stack 🔗

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import LinkedList from "./LinkedList";

class Stack {
  constructor() {
    this.linkedList = new LinkedList();
  }

  isEmpty() {
    return !this.linkedList.head;
  }

  peek() {
    if (this.isEmpty()) return null;
    return this.linkedList.head.value;
  }

  push(value) {
    this.linkedList.prepend(value);
  }

  pop() {
    return this.linkedList.deleteHead();
  }
}