From the course: Data Structures in JavaScript: BSTs, Queues, and Stacks
How to construct stacks - JavaScript Tutorial
From the course: Data Structures in JavaScript: BSTs, Queues, and Stacks
How to construct stacks
- [Instructor] You just completed a chapter learning about a data structure that uses the FIFO principle. And this chapter will be looking at a data structure that uses the LIFO principle. It really isn't so abstract. Concretely, in this chapter, you'll be learning about stacks and two of the pertinent functions and methods related to creating them. Stacks are linear data structures, and to add an element of data, you would push the element to the back, and to delete or remove an element, you would pop it from the end of the stack. Take a look at this code. It looks very similar to the code for the queue. Here, on line one through seven, you can see the declaration of a class for a stack. Now to add to your stack, you'll use the push function seen on lines 10 through 14. Now, a function to remove elements from your stack will use the pop function, as seen on lines 18 through 26. For the stack, when you remove the last value, it will return the value to you as well as remove it from your stack. So why not see what it looks like to create the stack by instantiating a new instance? Let's take a look here on line 33. And then on lines 43, 44 and 45, there are added elements to the stack. Using the push function. Using a console.log, you can see the stack now has those values that we pushed on line 43, 44 and 45. Take a look at line 46. We can use a console.log to see our current stack. And as we see, our output includes the values that we just pushed on line 43 through 45. Now for the removal of an element using the pop function. On line 48, you can see the value is returned and removed using a console.log. Okay, so pretty to the point in code and not too complicated, hopefully. Well, on that positive note, why not jump into Module 2, where you'll learn a little bit more about stacks and where they are used.
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.