Stack Data Structure
Stack Data Structure
A stack is a linear data structure that follows the principle of Last In First Out
(LIFO). This means the last element inserted inside the stack is removed first.
You can think of the stack data structure as the pile of plates on top of
another.
And, if you want the plate at the bottom, you must first remove all the plates
on top. This is exactly how the stack data structure works.
LIFO Principle of Stack
In programming terms, putting an item on top of the stack is called push and
removing an item is called pop.
Stack Push and Pop Operations
In the above image, although item 3 was kept last, it was removed first. This is
exactly how the LIFO (Last In First Out) Principle works.
1. A pointer called TOP is used to keep track of the top element in the stack.
2. When initializing the stack, we set its value to -1 so that we can check if the
stack is empty by comparing TOP == -1 .
3. On pushing an element, we increase the value of TOP and place the new
element in the position pointed to by TOP .
#include <stdlib.h>
#include <iostream>
#define MAX 10
int size = 0;
// Creating a stack
struct stack {
int items[MAX];
int top;
};
typedef struct stack st;
// Driver code
int main() {
int ch;
st *s = (st *)malloc(sizeof(st));
createEmptyStack(s);
push(s, 1);
push(s, 2);
push(s, 3);
push(s, 4);
printStack(s);
pop(s);
To reverse a word - Put all the letters in a stack and pop them out. Because
of the LIFO order of stack, you will get the letters in reverse order.
In compilers - Compilers use the stack to calculate the value of expressions
like 2 + 4 / 5 * (7 - 9) by converting the expression to prefix or postfix form.
In browsers - The back button in a browser saves all the URLs you have
visited previously in a stack. Each time you visit a new page, it is added on top
of the stack. When you press the back button, the current URL is removed
from the stack, and the previous URL is accessed.