Greetings! Today, we're delving into the concept of Stacks, a fundamental data structure in computer science. A stack operates similarly to a stack of plates: you add a plate to the top (Last In) and remove it from the top (First Out). This Last-In, First-Out (LIFO) principle is the core characteristic of a stack. In TypeScript, we can implement stacks using arrays due to their ease and efficiency. This lesson will illuminate the stack data structure, its operations, and their applications in TypeScript. Are you ready to start?
To create a stack, TypeScript uses arrays. For the push operation, we use the push() method to add an element to the end of the array. For the pop operation, there is the pop() function that removes the last element, mimicking the removal of the "top" element in a stack. Here's how it looks:
In the example provided, we push "John," "Mary," and "Steve" into the stack and then pop "Steve" from the stack.
Stack operations go beyond merely push and pop. For instance, to verify if a stack is empty, we can use the length property of the array. If it returns 0, the stack is empty. Conversely, if it returns a number greater than 0, the stack is not empty. To peek at the top element of the stack without popping it, we use the index this.stack[this.stack.length - 1].
Here's an example:
In this example, "Sam" is added (pushed), and then the topmost stack element, which is "Sam," is peeked at.
The isEmpty() method checks if there are any elements in the stack. This is useful in situations where we need to avoid errors caused by attempting to pop or peek an empty stack.
The peek() method allows us to view the topmost element without removing it. This is especially useful in algorithms that need to check or use the top element multiple times before deciding whether to remove it.
