Skip to content

Commit ba4c5c7

Browse files
authored
Update Stacks.md
1 parent 0231d19 commit ba4c5c7

File tree

1 file changed

+20
-0
lines changed
  • Basic Data Structures/Implementation of Stack in JavaScript

1 file changed

+20
-0
lines changed

Basic Data Structures/Implementation of Stack in JavaScript/Stacks.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,3 +103,23 @@ export default class Stack {
103103
}
104104
}
105105
```
106+
107+
> Notice that we can reverse the order of the stack: the bottom becomes the top and the top becomes the bottom. As such, we can use the array’s unshift and shift methods in place of push and pop, respectively.
108+
109+
```js
110+
class Stack {
111+
constructor(...items) {
112+
this.reverse = false;
113+
this.stack = [...items];
114+
}
115+
116+
push(...items) {
117+
return this.reverse
118+
? this.stack.unshift(...items)
119+
: this.stack.push(...items);
120+
}
121+
122+
pop() {
123+
return this.reverse ? this.stack.shift() : this.stack.pop();
124+
}
125+
}

0 commit comments

Comments
 (0)