Skip to content

Commit 46e47a7

Browse files
add stack
1 parent 4daf46d commit 46e47a7

File tree

4 files changed

+70
-1
lines changed

4 files changed

+70
-1
lines changed

Readme.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,7 @@ This repository contains Data Structures implementation using Javascript.
3030

3131
* [Doubly Linked List implementation](doubly-linked-list/doubly-linked-list.js)
3232

33+
### Stack
34+
35+
* [Stack implementation](stack/stack.js)
36+

linked-list/linked-list.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,10 @@ LinkedList.prototype.deleteAtIndex = function(index) {
5151
i++;
5252
}
5353

54+
const nodeToDelete = pre.next;
5455
pre.next = pre.next.next;
5556
this.size -= 1;
57+
return nodeToDelete;
5658
}
5759

5860
LinkedList.prototype.getNodeAtIndex = function(index) {
@@ -67,7 +69,7 @@ LinkedList.prototype.getNodeAtIndex = function(index) {
6769
i++;
6870
}
6971

70-
return pre.value;
72+
return pre;
7173
}
7274

7375
exports.LinkedList = LinkedList

stack/stack.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// Linked List
2+
// Pop / Push (add, remove) at one end in stack
3+
// Linked List
4+
5+
const { LinkedList } = require('../linked-list/linked-list');
6+
7+
function Stack() {
8+
this.stack = new LinkedList();
9+
}
10+
11+
// Stack is empty -- isEmpty
12+
// Find element at top -- peek
13+
// Push -- push
14+
// Pop --- pop
15+
16+
Stack.prototype.isEmpty = function() {
17+
return this.stack.size === 0;
18+
}
19+
20+
// Push and Pop at the same end
21+
// Linked List - we can access the first index in constant time
22+
// Push 1 ---> 1
23+
// Push 2 ---> 2 --- 1
24+
// Push 3 ---> 3 --- 2 --- 1
25+
Stack.prototype.push = function(value) {
26+
this.stack.addAtIndex(0, value);
27+
// console.log(this.stack);
28+
}
29+
30+
// Stack ---> 3 --- 2 --- 1
31+
// Pop ---> 2 --- 1
32+
// Pop ---> 1
33+
Stack.prototype.pop = function() {
34+
if (this.isEmpty()) {
35+
return null;
36+
}
37+
38+
const node = this.stack.deleteAtIndex(0);
39+
return node.value;
40+
}
41+
42+
Stack.prototype.peek = function() {
43+
if (this.isEmpty()) {
44+
return null;
45+
}
46+
47+
const node = this.stack.getNodeAtIndex(0);
48+
return node.value;
49+
}
50+
51+
exports.Stack = Stack;

stack/test-stack.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
const { Stack } = require("./stack");
2+
3+
const stack = new Stack();
4+
5+
stack.push(1);
6+
console.log(stack.peek())
7+
stack.push(2);
8+
console.log(stack.peek())
9+
stack.push(3);
10+
console.log(stack.peek())
11+
console.log(stack.pop());
12+
console.log(stack.peek());

0 commit comments

Comments
 (0)