Skip to content

Commit c25f3f3

Browse files
committed
Stack on singly linked list
1 parent c6cd0b4 commit c25f3f3

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

JavaScript/1-stack.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
'use strict';
2+
3+
class Stack {
4+
constructor() {
5+
this.last = null;
6+
}
7+
push(item) {
8+
const prev = this.last;
9+
const element = { prev, item };
10+
this.last = element;
11+
}
12+
pop() {
13+
const element = this.last;
14+
if (!element) return null;
15+
this.last = element.prev;
16+
return element.item;
17+
}
18+
}
19+
20+
// Usage
21+
22+
const obj1 = { name: 'first' };
23+
const obj2 = { name: 'second' };
24+
const obj3 = { name: 'third' };
25+
26+
const list = new Stack();
27+
list.push(obj1);
28+
list.push(obj2);
29+
list.push(obj3);
30+
31+
console.dir(list.pop());
32+
console.dir(list.pop());
33+
console.dir(list.pop());
34+
console.dir(list.pop());

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy