-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.js
84 lines (74 loc) · 1.92 KB
/
queue.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Queue is a linear data structure that follows the First In, First Out (FIFO) principle.
// It has two main operations: enqueue (add an element to the end) and dequeue (remove the front element).
// Queues are commonly used in algorithms like breadth-first search (BFS) and in task scheduling.
// Node class represents an element in the queue
/**
* Represents a node in a queue.
* Each node contains a value and a reference to the next node in the queue.
*/
class Node {
/**
* Creates a new Node.
* @param {*} value - The value to be stored in the node.
*/
constructor(value) {
this.value = value;
this.next = null;
}
}
/**
* Represents a queue.
* The queue keeps track of its first, last, and length.
*/
class Queue {
/**
* Creates a new Queue.
* @param {*} value - The value for the first node in the queue.
*/
constructor(value) {
const newNode = new Node(value);
this.first = newNode;
this.last = newNode;
this.length = 1;
}
/**
* Adds a new element to the end of the queue.
* @param {*} value - The value for the new node.
* @returns {Queue} The updated queue.
*/
enqueue(value) {
const newNode = new Node(value);
if (this.length === 0) {
this.first = newNode;
this.last = newNode;
}
this.last.next = newNode;
this.last = newNode;
this.length++;
return this;
}
/**
* Removes and returns the first element from the queue.
* @returns {*} The value of the removed node or undefined if the queue is empty.
*/
dequeue() {
if (this.length === 0) {
return undefined;
}
let temp = this.first;
if (this.length === 1) {
this.first = null;
this.last = null;
}
this.first = this.first.next;
temp.next = null;
this.length--;
return temp;
}
}
// Example usage
const myQueue = new Queue(1);
myQueue.enqueue(1);
myQueue.enqueue(2);
// myQueue.dequeue();
console.log(myQueue);