Implement Stack interface using linked list
// linked-list-as-stack
function stack() {
this.head = null;
}
stack.prototype.print = function() {
let curr = this.head
while(curr) {
console.log(curr.val)
curr = curr.next
}
}
stack.prototype.push = function(val) {
if (!this.head) {
this.head = {
val: val,
next: null
}
} else {
let pushed = {
val: val,
next: this.head
}
this.head = pushed;
}
}
stack.prototype.pull = function() {
let pulled;
if (!this.head) {
pulled = null;
} else {
pulled = this.head;
this.head = this.head.next;
}
return pulled;
}
let st = new stack();
st.push(5);
st.push(4);
st.push(3);
st.push(2);
st.push(1);
st.print();
st.pull();
st.print();