Skip to content

Commit c4fd167

Browse files
committed
Queue and Stack
1 parent 2418422 commit c4fd167

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed

Algorithm/Queue/Queue.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Queue {
2+
// Array is used to implement a Queue
3+
constructor() {
4+
this.items = [];
5+
}
6+
7+
// enqueue function
8+
enqueue(element) {
9+
// adding element to the queue
10+
this.items.push(element);
11+
}
12+
13+
// dequeue function
14+
dequeue() {
15+
// removing element from the queue
16+
// returns underflow when called
17+
// on empty queue
18+
if (this.isEmpty()) return "Underflow";
19+
return this.items.shift();
20+
}
21+
22+
front() {
23+
// returns the Front element of
24+
// the queue without removing it.
25+
if (this.isEmpty()) return "No elements in Queue";
26+
return this.items[0];
27+
}
28+
29+
// isEmpty function
30+
isEmpty() {
31+
// return true if the queue is empty.
32+
return this.items.length == 0;
33+
}
34+
35+
// printQueue()
36+
printQueue() {
37+
var str = "";
38+
for (var i = 0; i < this.items.length; i++) str += this.items[i] + " ";
39+
return str;
40+
}
41+
}

Algorithm/Stack/Stack.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Stack {
2+
// Array is used to implement stack
3+
constructor() {
4+
this.items = [];
5+
}
6+
7+
// Functions to be implemented
8+
// push(item)
9+
push(element) {
10+
// push element into the items
11+
this.items.push(element);
12+
}
13+
14+
// pop()
15+
pop() {
16+
// return top most element in the stack
17+
// and removes it from the stack
18+
// Underflow if stack is empty
19+
if (this.items.length == 0) return "Underflow";
20+
return this.items.pop();
21+
}
22+
23+
// peek()
24+
peek() {
25+
// return the top most element from the stack
26+
// but does'nt delete it.
27+
return this.items[this.items.length - 1];
28+
}
29+
30+
// isEmpty()
31+
isEmpty() {
32+
// return true if stack is empty
33+
return this.items.length == 0;
34+
}
35+
36+
// printStack()
37+
printStack() {
38+
var str = "";
39+
for (var i = 0; i < this.items.length; i++) str += this.items[i] + " ";
40+
return str;
41+
}
42+
}

0 commit comments

Comments
 (0)