File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed
Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @author Rashik Ansar
3+ *
4+ * Implementation of Queue Data structure
5+ * Queue follows FIFO (First In First Out) Principle
6+ */
7+
8+ class Node {
9+ constructor ( data ) {
10+ this . data = data ;
11+ this . next = null ;
12+ }
13+ }
14+
15+ class Queue {
16+ constructor ( ) {
17+ this . first = null ;
18+ this . last = null ;
19+ this . size = 0 ;
20+ }
21+
22+ /**
23+ * Adding data to the end of queue
24+ * @param {* } data Data to add in the queue
25+ * @returns {Queue } Returns the queue after adding new data
26+ */
27+ enqueue ( data ) {
28+ let newNode = new Node ( data ) ;
29+ if ( ! this . first ) {
30+ this . first = newNode ;
31+ this . last = newNode ;
32+ } else {
33+ this . last . next = newNode ;
34+ this . last = newNode ;
35+ }
36+ this . size ++ ;
37+ return this ;
38+ }
39+
40+ /**
41+ * Removing data from the beginning of the queue
42+ * @returns Data that is removing from queue
43+ */
44+ dequeue ( ) {
45+ if ( ! this . first ) {
46+ throw Error (
47+ 'UNDERFLOW::: The queue is empty, there is nothing to remove'
48+ ) ;
49+ }
50+ let temp = this . first ;
51+ if ( this . first === this . last ) {
52+ this . last = null ;
53+ }
54+ this . first = this . first . next ;
55+ this . size -- ;
56+ return temp . data ;
57+ }
58+
59+ /**
60+ * @returns First element in the queue
61+ */
62+ peek ( ) {
63+ if ( ! this . first ) {
64+ throw Error ( 'Stack is empty' ) ;
65+ }
66+ return this . first . data ;
67+ }
68+ }
You can’t perform that action at this time.
0 commit comments