File tree Expand file tree Collapse file tree 4 files changed +70
-1
lines changed Expand file tree Collapse file tree 4 files changed +70
-1
lines changed Original file line number Diff line number Diff line change @@ -30,3 +30,7 @@ This repository contains Data Structures implementation using Javascript.
30
30
31
31
* [ Doubly Linked List implementation] ( doubly-linked-list/doubly-linked-list.js )
32
32
33
+ ### Stack
34
+
35
+ * [ Stack implementation] ( stack/stack.js )
36
+
Original file line number Diff line number Diff line change @@ -51,8 +51,10 @@ LinkedList.prototype.deleteAtIndex = function(index) {
51
51
i ++ ;
52
52
}
53
53
54
+ const nodeToDelete = pre . next ;
54
55
pre . next = pre . next . next ;
55
56
this . size -= 1 ;
57
+ return nodeToDelete ;
56
58
}
57
59
58
60
LinkedList . prototype . getNodeAtIndex = function ( index ) {
@@ -67,7 +69,7 @@ LinkedList.prototype.getNodeAtIndex = function(index) {
67
69
i ++ ;
68
70
}
69
71
70
- return pre . value ;
72
+ return pre ;
71
73
}
72
74
73
75
exports . LinkedList = LinkedList
Original file line number Diff line number Diff line change
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 ;
Original file line number Diff line number Diff line change
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 ( ) ) ;
You can’t perform that action at this time.
0 commit comments