Skip to content

Commit 0129ca4

Browse files
authored
Merge pull request #15 from Hydro95/Queue
Added Queue Data Structure
2 parents 4f2361c + 11964de commit 0129ca4

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

Data Structures/Queue/Queue.js

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/* Queue
2+
* A Queue is a data structure that allows you to add an element to the end of
3+
* a list and remove the item at the front. A queue follows a "First In First Out"
4+
* system, where the first item to enter the queue is the first to be removed. This
5+
* implementation uses an array to store the queue.
6+
*/
7+
8+
//Functions: enqueue, dequeue, peek, view, length
9+
10+
var Queue = function() {
11+
12+
//This is the array representation of the queue
13+
this.queue = [];
14+
15+
//Add a value to the end of the queue
16+
this.enqueue = function(item) {
17+
this.queue[this.queue.length] = item;
18+
}
19+
20+
//Removes the value at the front of the queue
21+
this.dequeue = function() {
22+
if (this.queue.length === 0) {
23+
return "Queue is Empty";
24+
}
25+
26+
var result = this.queue[0];
27+
this.queue.splice(0, 1); //remove the item at position 0 from the array
28+
29+
return result;
30+
}
31+
32+
//Return the length of the queue
33+
this.length = function() {
34+
return this.queue.length;
35+
}
36+
37+
//Return the item at the front of the queue
38+
this.peek = function() {
39+
return this.queue[0];
40+
}
41+
42+
//List all the items in the queue
43+
this.view = function() {
44+
console.log(this.queue);
45+
}
46+
}
47+
48+
//Implementation
49+
var myQueue = new Queue();
50+
51+
myQueue.enqueue(1);
52+
myQueue.enqueue(5);
53+
myQueue.enqueue(76);
54+
myQueue.enqueue(69);
55+
myQueue.enqueue(32);
56+
myQueue.enqueue(54);
57+
58+
myQueue.view();
59+
60+
console.log("Length: " + myQueue.length());
61+
console.log("Front item: " + myQueue.peek());
62+
console.log("Removed " + myQueue.dequeue() + " from front.");
63+
console.log("New front item: " + myQueue.peek());
64+
console.log("Removed " + myQueue.dequeue() + " from front.");
65+
console.log("New front item: " + myQueue.peek());
66+
myQueue.enqueue(55);
67+
console.log("Inserted 55");
68+
console.log("New front item: " + myQueue.peek());
69+
70+
for (var i = 0; i < 5; i++) {
71+
myQueue.dequeue();
72+
myQueue.view();
73+
}
74+
75+
console.log(myQueue.dequeue());

0 commit comments

Comments
 (0)