Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

sakethk
sakethk

Posted on

     

Implementing Stack in javascript

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

image

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}}
Enter fullscreen modeExit fullscreen mode

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
Enter fullscreen modeExit fullscreen mode

Thank you!!
Cheers!!!

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
ramu profile image
Ramu
  • Location
    India
  • Work
    Frontend Engineer at Epam systems
  • Joined

Cristal clear.. Thanks

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Computer jock, Programmer, Technology enthusiast and Math ❤️ er.
  • Location
    India
  • Work
    UI Developer at Observe.ai
  • Joined

More fromsakethk

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp