Hello 👋,
This is an article on implementing stack data structure in javascript
We already know stack is data structure. It has methods likepush
,pop
,top
,size
andisEmpty
push
It will insert the element at first.
pop
It will delete and returns the first element.
top
It will return first element
size
It will return size of an stack i.e no of elements in stack
isEmpty
It will returntrue
if stack doesn't have any elements otherwise it will returnfalse
classStack{constructor(){this.list=[]}push(ele){this.list.unshift(ele)}pop(){returnthis.list.shift()}top(){returnthis.list[0]}size(){returnthis.list.length}isEmpty(){returnthis.list.length===0}}
Usage
constmystack=newStack()mystack.isEmpty()// truemystack.push("a")// returns undefined but it will add element to listmystack.push("b")mystack.push("c")mystack.isEmpty()// falsemystack.top()// cmystack.pop()// cmystack.top()// bmystack.size()// 2
Thank you!!
Cheers!!!
Top comments(1)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse