Module 2-1
Module 2-1
Table of contents
Module 2
Module-II:
Stacks: Introduction, Stack Operations, Stack Implementation using Arrays, Applications of
Stacks.
Queues: Introduction, Queue Operations, Queue Implementation using Arrays, Different
Types of Queues: Circular Queues, Double-Ended Queues, Priority Queues, Applications of
Queues.
Textbook 2: Ch. 6.1 to 6.3, Ch. 8.1 to 8.2.
Introduction
Stacks and Queues are linear data structures widely used in programming for organizing and manipulating data.They are
implemented using arrays or linked lists, depending on the requirements and constraints of the problem.
Stacks
A stack is a LIFO (Last In First Out — the element placed at last can be accessed at first) structure which can be
commonly found in many programming languages. This structure is named as “stack” because it resembles a real-
world stack — a stack of plates.
Stack operations
Given below are the 2 basic operations that can
be performed on a stack.
• Push: Insert an element on to the top of
the stack.
• Pop: Delete the topmost element and
return it.
Applications of stacks
• Expression Evaluation: Convert infix expressions to postfix or prefix and evaluate them.
• Backtracking: Used in algorithms like solving mazes or puzzles.
• Function Call Management: Used to implement function calls in recursion programming. The runtime stack stores
function calls, parameters, and return addresses during program execution.
1
CEC 18CS652: Introduction to Data Structures and Algorithms
Insert/Push Operation
The push operation adds an element to the top of the stack.
Condition: Check if the stack is full (Overflow condition) before pushing.
Steps:
1. Increment the `top` index.
2. Insert the element at the position indicated by `top`.
if (top == maxSize - 1)
printf("Stack Overflow");
else {
top++;
stack[top] = value;
}
Delete/Pop Operation
The **pop operation removes the topmost element from the stack.
-Condition: Check if the stack is empty (Underflow condition) before popping.
-Steps:
1. Access the element at the `top` index.
2. Decrement the `top` index.
if (top == -1)
printf("Stack Underflow");
else {
value = stack[top];
top--;
}
Display
To display the elements of the stack:
1. Traverse the array from the `top` index to `0`.
2. Print each element.
for (i = top; i >= 0; i--)
printf("%d ", stack[i]);
#include <stdio.h>
#define MAX 100 // Maximum size of the stack
// Stack structure
typedef struct {
int arr[MAX];
int top;
} Stack;
2
CEC 18CS652: Introduction to Data Structures and Algorithms
int main() {
Stack stack;
stack.top = -1; // Initialize the stack manually
// Example operations on the stack
push(&stack, 10);
push(&stack, 20);
push(&stack, 30);
printf("Top element is: %d\n", peek(&stack));
printf("Popped element: %d\n", pop(&stack));
printf("Popped element: %d\n", pop(&stack));
printf("Popped element: %d\n", pop(&stack));
printf("Popped element: %d\n", pop(&stack)); // Attempt to pop from an empty
stack
return 0;
}
Example:
For the expression `A + B * C ^ D - E`:
1. `C ^ D` (Exponentiation is evaluated first).
2. `B * (Result of C ^ D)` (Multiplication).
3. `A + (Result of B * C ^ D)` (Addition).
4. `(Result of A + ...) - E` (Subtraction).
3
CEC 18CS652: Introduction to Data Structures and Algorithms
Infix Expression:
The provided infix expression is
`X ^ Y ^ Z - M + N + P * I / Q`
(a) Postfix Expression for `X ^ Y ^ Z - M + N + P * I / Q`:
1. Exponentiation: `X ^ Y ^ Z` → `XYZ^^`.
2. Subtract `M`: `XYZ^^ - M` → `XYZ^^M-`.
3. Add `N`: `XYZ^^M- + N` → `XYZ^^M-N+`.
4. Multiply and divide: `P * I / Q` → `PI*Q/`.
5. Add: `(Result of XYZ^^M-N+) + (PI*Q/)` → `XYZ^^M-N+PI*Q/+`.
Final Postfix**: `XYZ^^M-N+PI*Q/+`.
(b) Prefix Expression for** `X ^ Y ^ Z - M + N + P * I / Q`:
1. Exponentiation: `X ^ Y ^ Z` → `^X^YZ`.
2. Subtract `M`: `^X^YZ - M` → `-^X^YZM`.
3. Add `N`: `-^X^YZM + N` → `+ -^X^YZM N`.
4. Multiply and divide: `P * I / Q` → `/ * PIQ`.
4
CEC 18CS652: Introduction to Data Structures and Algorithms
- Infix to Prefix:
- Reverse the infix expression.
- Apply the infix-to-postfix method on the reversed expression.
- Reverse the resulting postfix expression.
5
CEC 18CS652: Introduction to Data Structures and Algorithms
Additional Problems:
Convert the following infix to prefix : (A-B/C)*(A/K-L)
Convert the following infix to postfix : A+B*(C^D-E)^(F+G*H)-I
Convert the following postfix to prefix: ABC/-AK/L-*
Convert the following prefix to postfix: *-A/BC-/AKL
6
CEC 18CS652: Introduction to Data Structures and Algorithms
Queues
Introduction
Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is open at both its ends. One
end is always used to insert data (enqueue) and the other is used to remove data (dequeue). Queue follows First-In-
First-Out methodology, i.e., the data item stored first will be accessed first.
As in stacks, a queue can also be implemented using Arrays, Linked-lists, Pointers and Structures. For the sake of
simplicity, we shall implement queues using one-dimensional array.
7
CEC 18CS652: Introduction to Data Structures and Algorithms
Linear Queues
.
Queue Implementation using Array
Before we implement actual operations, first follow the below steps to create an empty queue.
• Step 1 Include header files and define a constant 'SIZE' with specific value.
• Step 2 Declare user defined functions which are used in queue implementation.
• Step 3 Create 1 dimensional array with above defined SIZE (INT QUEUE[SIZE])
• Step 4 Define two int variables 'FRONT' & 'REAR' and initialize both with '-1'.
• Step 5 Then implement main method by using suitable function calls to perform operation selected by the
user on queue.
Implementation
#include<stdio.h>
#define SIZE 10
void enQueue(int);
void deQueue();
void display();
int queue[SIZE], front = -1, rear = -1;
void main(){
int value, choice;
while(1){
printf("\n\n***** MENU *****\n");
printf("1. Insertion\n2. Deletion\n3. Display\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
8
CEC 18CS652: Introduction to Data Structures and Algorithms
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d",&value);
enQueue(value);
break;
case 2: deQueue();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong selection!!! Try again!!!");
}
}
}
void enQueue(int value){
if(rear == SIZE-1)
printf("\nQueue is Full!!! Insertion is not possible!!!");
else{
if(front == -1)
front = 0;
rear++;
queue[rear] = value;
printf("\nInsertion success!!!");
}
}
void deQueue(){
if(front == rear)
printf("\nQueue is Empty!!! Deletion is not possible!!!");
else{
printf("\nDeleted : %d", queue[front]);
front++;
if(front == rear)
front = rear = -1;
}
}
void display(){
if(rear == -1)
printf("\nQueue is Empty!!!");
else{
int i;
printf("\nQueue elements are:\n");
for(i=front; i<=rear; i++)
printf("%d\t",queue[i]); } }
9
CEC 18CS652: Introduction to Data Structures and Algorithms
10
CEC 18CS652: Introduction to Data Structures and Algorithms
Implementation
#include <stdio.h>
# define max 6
int queue[max]; // array declaration
int front=-1;
int rear=-1;
int main(){
int choice=1,x; // variables declaration
while(choice<4 && choice!=0) // while loop
{
printf("\n Press 1: Insert an element");
printf("\nPress 2: Delete an element");
printf("\nPress 3: Display the element");
printf("\nEnter your choice");
scanf("%d", &choice);
switch(choice){
case 1:
printf("Enter the element which is to be inserted");
scanf("%d", &x);
enqueue(x);
break;
case 2:
dequeue();
break;
case 3:
display();
}
}
return 0;
}
11
CEC 18CS652: Introduction to Data Structures and Algorithms
Priority Queues
A priority queue is an abstract data type that behaves similarly to the normal queue except that each element has
some priority, i.e., the element with the highest priority would come first in a priority queue. The priority of the
elements in a priority queue will determine the order in which elements are removed from the priority queue.
The priority queue supports only comparable elements, which means that the elements are either arranged in an
ascending or descending order.
12
CEC 18CS652: Introduction to Data Structures and Algorithms
13
CEC 18CS652: Introduction to Data Structures and Algorithms
Here is a simple code in C 2D matrix: C program to store temperature of two cities of a week and display it.
#include <stdio.h>
const int CITY = 2;
const int WEEK = 7;
int main(){
int temperature[CITY][WEEK];
// Using nested loop to store values in a 2d array
for (int i = 0; i < CITY; ++i){
for (int j = 0; j < WEEK; ++j){
printf("City %d, Day %d: ", i + 1, j + 1);
scanf("%d", &temperature[i][j]);
}
}
printf("\nDisplaying values: \n\n");
// Using nested loop to display vlues of a 2d array
for (int i = 0; i < CITY; ++i){
for (int j = 0; j < WEEK; ++j){
printf("City %d, Day %d = %d\n", i + 1, j + 1, temperature[i][j]);
}
}
return 0;}
Three-dimensional array:
C Program to store and print 12 values entered by the user
#include <stdio.h>
int main(){
int test[2][3][2];
printf("Enter 12 values: \n");
for (int i = 0; i < 2; ++i){
for (int j = 0; j < 3; ++j){
for (int k = 0; k < 2; ++k){
scanf("%d", &test[i][j][k]);
}
}
}
// Printing values with proper index.
14
CEC 18CS652: Introduction to Data Structures and Algorithms
printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i){
for (int j = 0; j < 3; ++j){
for (int k = 0; k < 2; ++k){
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}
return 0;}
#include <stdio.h>
int main(){
float a[2][2], b[2][2], result[2][2];
// Taking input using nested for loop
printf("Enter elements of 1st matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j){
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%f", &a[i][j]);
}
// Taking input using nested for loop
printf("Enter elements of 2nd matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j){
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}
// adding corresponding elements of two arrays
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j){
result[i][j] = a[i][j] + b[i][j];
}
15
CEC 18CS652: Introduction to Data Structures and Algorithms
#include <stdio.h>
// function to get matrix elements entered by the user
void getM (int matrix[][10], int row, int column) {
printf("\nEnter elements: \n");
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}
}
// function to multiply two matrices
void multiplyM (int first[][10], int second[][10],
int result[][10], int r1, int c1, int r2, int c2) {
// Initializing elements of matrix mult to 0.
for (int i = 0; i < r1; ++i) {
for (int j = 0; j < c2; ++j) {
result[i][j] = 0;
}
}
// Multiplying first and second matrices and storing it in result
for (int i = 0; i < r1; ++i) {
for (int j = 0; j < c2; ++j) {
16
CEC 18CS652: Introduction to Data Structures and Algorithms
17
CEC 18CS652: Introduction to Data Structures and Algorithms
18