Stack
Last updated
Last updated
class Queue {
constructor() {
this.mainStack = []
this.subStack = []
}
push(data) {
while (this.mainStack.length) {
this.subStack.push(this.mainStack.shift())
}
this.subStack.push(data)
while (this.subStack.length) {
this.mainStack.push(this.subStack.shift())
}
}
pop() {
return this.mainStack.shift()
}
peak() {
return this.mainStack[this.mainStack.length - 1]
}
isEmpty() {
return !this.mainStack.length
}
}function Node(data) {
this.data = data
this.next = null
}
class Stack {
constructor() {
this.top = null
}
push(data) {
const n = new Node(data)
n.next = this.top
this.top = n
}
pop() {
if (!this.top) {
throw new Error('stack underflow')
}
const item = this.top
this.top = item.next
return item.data
}
peek() {
if (!this.top) {
throw new Error('stack underflow')
}
return this.top.data
}
isEmpty() {
return !this.top
}
}
const stack = new Stack()