|
class Node { |
|
constructor(val) { |
|
this.value = val; |
|
this.next = null; |
|
} |
|
} |
|
|
|
/** |
|
* push and pop to be constant time |
|
*/ |
|
class Stack { |
|
constructor(){ |
|
this.first = null; |
|
this.last = null; |
|
this.size = 0; |
|
} |
|
|
|
push(val) { |
|
let newNode = new Node(val); |
|
if(!this.first){ |
|
this.first = newNode; |
|
this.last = newNode; |
|
} else { |
|
newNode.next = this.first; |
|
this.first = newNode; |
|
} |
|
|
|
return ++this.size; |
|
} |
|
|
|
pop(){ |
|
if(!this.first) return null; |
|
let removedNode = this.first; |
|
|
|
if(this.first === this.last) { |
|
this.last = null; |
|
} |
|
this.first = removedNode.next; |
|
removedNode.next =null; |
|
this.size--; |
|
return removedNode.value; |
|
} |
|
} |
|
|
|
let stack = new Stack(); |
|
stack.push("aaa"); |
|
stack.push("bbb"); |
|
stack.push("ccc"); |