DSU Vol 2 Notes (3rd Chapter)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

3.

Stack & Queue

Definition of Stack -:

A stack is a fundamental data structure that follows the Last In, First Out
(LIFO) principle. In a stack, the last element added is the first one to be
removed. Think of it like a stack of plates where you add or remove plates from
the top.

 The operations on a stack are often referred to as "push" (to add an


element) and "pop" (to remove the top element).

Key features of a stack:

1. LIFO (Last In, First Out): The last element added is the first one to be
removed.

2. Operations:

 Push: Adds an element to the top of the stack.


 Pop: Removes the element from the top of the stack.

3. Implementation:

 A stack can be implemented using various data structures like arrays or


linked lists.
4. Usage:

 Stacks are used in many algorithms and applications, such as function


call management in programming languages (call stack), expression
evaluation, backtracking algorithms, and managing undo operations in
software applications.

Stack Operations

Push Operation

The push operation adds an element to the top of the stack.

Algorithm for Push:

1. Check if the stack is full (in the case of a fixed-size array


implementation).

 If the stack is full, display an overflow message.


 If the stack is not full, proceed to the next step.

2. Increment the top pointer.

 top = top + 1;`

3. Assign the new element to the position indicated by the top pointer.

 stack[top] = newElement;`
Initial Stack: [1, 2, 3]

Push 4:

After Push: [1, 2, 3, 4]

Pop Operation:

The pop operation removes the element from the top of the stack.

Algorithm for Pop:

1. Check if the stack is empty.

 If the stack is empty, display an underflow message.


 If the stack is not empty, proceed to the next step.

2. Access the element at the top position.

 poppedElement = stack[top];`

3. Decrement the top pointer.

 top = top - 1;`

4. Return or use the popped element.

Initial Stack: [1, 2, 3, 4]

Pop:

After Pop: [1, 2, 3]

Popped Element: 4
Example Code (in C):

#define MAX_SIZE 10
int stack[MAX_SIZE];
int top = -1;

// Push operation
void push(int newElement) {
if (top == MAX_SIZE - 1) {
printf("Stack Overflow. Cannot push %d.\n", newElement);
return;
}

top = top + 1;
stack[top] = newElement;
}

// Pop operation
int pop() {
if (top == -1) {
printf("Stack Underflow. Cannot pop.\n");
return -1; // Or some sentinel value indicating underflow
}

int poppedElement = stack[top];


top = top - 1;
return poppedElement;
}

 C Program for Stack Operations using Switch Case

#include <stdio.h>

#define MAX_SIZE 10

// Stack structure
struct Stack {
int arr[MAX_SIZE];
int top;
};

// Function to initialize the stack


void initialize(struct Stack stack) {
stack->top = -1;
}

// Function to check if the stack is full


int isFull(struct Stack stack) {
return stack->top == MAX_SIZE - 1;
}

// Function to check if the stack is empty


int isEmpty(struct Stack stack) {
return stack->top == -1;
}

// Function to push an element onto the stack


void push(struct Stack stack, int element) {
if (isFull(stack)) {
printf("Stack is full. Cannot push %d.\n", element);
return;
}

stack->arr[++stack->top] = element;
printf("Element %d pushed successfully.\n", element);
}

// Function to pop an element from the stack


void pop(struct Stack stack) {
if (isEmpty(stack)) {
printf("Stack is empty. Cannot pop.\n");
return;
}

printf("Element %d popped successfully.\n", stack->arr[stack->top--]);


}

// Function to display the elements of the stack


void display(struct Stack stack) {
if (isEmpty(stack)) {
printf("Stack is empty.\n");
return;
}

printf("Stack elements: ");


for (int i = 0; i <= stack->top; ++i) {
printf("%d ", stack->arr[i]);
}
printf("\n");
}

int main() {
struct Stack stack;
initialize(&stack);

int choice, element;

do {
printf("\nStack Menu:\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("4. Quit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter the element to push: ");
scanf("%d", &element);
push(&stack, element);
break;

case 2:
pop(&stack);
break;

case 3:
display(&stack);
break;

case 4:
printf("Exiting the program. Goodbye!\n");
break;

default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 4);

return 0;
}

Applications of Stack

Here are some common applications of stacks:

1. Function Call Management (Call Stack):

 Stacks are used in programming languages to manage function calls.


When a function is called, its local variables and return address are
pushed onto the stack, and when the function completes, they are popped
off.

2. Expression Evaluation:
 Stacks are employed to evaluate expressions, especially infix to postfix or
infix to prefix conversions. The stack helps in maintaining the order of
operations.

3. Undo Mechanisms in Software:

 Many software applications, like text editors or graphic design tools, use
stacks to implement undo functionalities. Each operation is pushed onto
the stack, and undo pops the last operation.

4. Backtracking Algorithms:

 Stacks are crucial in backtracking algorithms, like in-depth first search


(DFS). The stack is used to store the sequence of decisions made during
exploration and backtrack when necessary.

5. Browser History:

 The "Back" button in web browsers uses a stack to keep track of visited
pages. Each time a new page is visited, it is pushed onto the stack, and
going back pops the last visited page.

6. Parsing in Compilers:

 Stacks play a vital role in syntax analysis phase during compilation. They
are used to store and manage grammar rules and symbols for parsing.

7. Memory Management:

 Stacks are used in memory management, such as managing function call


frames and local variables. The stack memory is automatically
deallocated when a function exits.

8. Balancing Symbols:
 Stacks are employed to check the balance of symbols like parentheses,
braces, and brackets in expressions. Each opening symbol is pushed onto
the stack, and a closing symbol pops it.

9. Task Scheduling:

 Operating systems use stacks to manage the execution of processes and


their interruptions. The stack keeps track of the execution context for
each process.

10. Managing Undo/Redo Operations:

 Besides individual software applications, stacks are used in more


complex systems to manage a sequence of undo and redo operations
across multiple actions.

You might also like