JavaScript: Stack Data Structure
class Stack { | |
constructor() { | |
this.items = []; | |
} | |
push(elements) { | |
this.items.push(elements); | |
} | |
pop() { | |
return this.items.pop(); | |
} | |
peek() { | |
return this.items[this.items.length - 1]; | |
} | |
isEmpty() { | |
return this.items.length === 0; | |
} | |
clear() { | |
this.items = []; | |
} | |
size() { | |
return this.items.length; | |
} | |
toString() { | |
return this.items.toString(); | |
} | |
} | |
const books = new Stack(); | |
books.push("The Hobbit"); | |
books.push("LOTR: The Fellowship of the Ring"); | |
books.push("LOTR: The Two Towers"); | |
books.push("LOTR: The Return of the King"); | |
console.log(books.peek()); // => "LOTR: The Return of the King" | |
books.pop(); | |
books.pop(); | |
console.log(books.toString()); // => "The Hobbit,LOTR: The Fellowship of the Ring" | |
console.log(books.size()); // => 2 | |
books.clear(); | |
console.log(books.isEmpty()); // => true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment