This repository was archived by the owner on Sep 7, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathqueue.js
More file actions
68 lines (63 loc) · 1.28 KB
/
queue.js
File metadata and controls
68 lines (63 loc) · 1.28 KB
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
/**
* @author Rashik Ansar
*
* Implementation of Queue Data structure
* Queue follows FIFO (First In First Out) Principle
*/
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class Queue {
constructor() {
this.first = null;
this.last = null;
this.size = 0;
}
/**
* Adding data to the end of queue
* @param {*} data Data to add in the queue
* @returns {Queue} Returns the queue after adding new data
*/
enqueue(data) {
let newNode = new Node(data);
if (!this.first) {
this.first = newNode;
this.last = newNode;
} else {
this.last.next = newNode;
this.last = newNode;
}
this.size++;
return this;
}
/**
* Removing data from the beginning of the queue
* @returns Data that is removing from queue
*/
dequeue() {
if (!this.first) {
throw Error(
'UNDERFLOW::: The queue is empty, there is nothing to remove'
);
}
let temp = this.first;
if (this.first === this.last) {
this.last = null;
}
this.first = this.first.next;
this.size--;
return temp.data;
}
/**
* @returns First element in the queue
*/
peek() {
if (!this.first) {
throw Error('Stack is empty');
}
return this.first.data;
}
}