Reputation: 159
So I made a function to push user-inputted strings to a stack by using the built in .push(e)
function like so:
push() {
const arrays = this.array.push(String(this.userInput))
console.log(this.array)
}
and with every click of the push button the console updates the array pushing whatever the user has inputted into an HTML text field which I have also made. I showed it to a friend and they told me that this method was sort of cheating as I'm making a Stack of stacks and that there is a way to...
Implement a Stack using only an index, a count, and an array.
Conceptually I know what these are, the index is an objects position in a given array, and an array is a collection of objects of the same variable types and a count is ostensibly a count (correct me if I'm wrong?). However tying these concepts together to implement a stack is a little beyond me as a first semester computer science student is there a lay-mans terms way of explaining how these things can be tied together to implement a stack?
Upvotes: 0
Views: 256
Reputation: 370759
To do what you're doing without using the built-in push
method, just assign to the index at the current length of the array. No need to keep track of any other variables:
push() {
this.array[this.array.length] = String(this.userInput);
// if you also need your implementation to return the new length, then:
return this.array.length;
}
Or, for pop
:
pop() {
const item = this.array[this.array.length - 1];
this.array.length = Math.max(this.array.length - 1, 0);
return item;
}
Keep in mind that push
returns the new length of the array, so const arrays = this.array.push(String(this.userInput))
won't give you an array in return.
Upvotes: 1