Stack Part 3
Table of Contents
Stack: Introduction
push in a stack is putting an item on top of the stack.
pop in a stack is taking out the top item in the stack.
Stacks are used extensively in a lot of places.
Compilers and Parsers – Expression evaluation is done by stacks by postfix or prefix using stacks in compilers.
Activation Records – An activation record is data that keeps track of the procedure activities during the runtime of a program.
When the function is called, an activation record is created for it and keeps track of parameters and information like local variables, return address, static and dynamic links, and the return value.
This activation record is the fundamental part of programming languages and is implemented using a stack.
Web Browsers – Web Browsers use a stack to keep track of URLs that you have visited previously. When you visit a new page, it is added to the stack and when you hit the back button, the stack is popped and the previous URL is accessed.
Implementing Stacks
Stack Methods
There are various functions that are associated with a stack. They are,
stack.isEmpty()
The stack.isEmpty() method returns True if the stack is empty. Else, returns False
stack.length()
The stack.length() method returns the length of the stack.
stack.top()
The stack.top() method returns a pointer/reference to the top element in the stack.
stack.push(x)
The stack.push() method inserts the element, x to the top of the stack.
stack.pop()
The stack.pop() method removes the top element of the stack and returns it.
Stack Implementations
In Python, we can implement the stack by various methods. We are going to dive into two of the methods - the common method and the efficient method.
Stack using a List
We use the list methods append and pop to implement a Stack.
Stack using collection.Deque
Python collections are container classes that are used for data collection storage. They are highly optimized, are really fast, and have lots of methods built-in.
Deque is one such python collection that is used for inserting and removing items. We can use it to create a faster implementation of a stack.
Practice Stacks
Once you are done with understanding the stack and the basic implementation, practice the following problems and problem-sets in order to get a strong grasp on stacks.
We have learned the implementation, importance, and application of stacks. This is one of the most important data structures to know and it is extensively asked in the computer science industry. It is important to have strong knowledge on this topic as it would give you an edge.