You are on page 1of 133

Foundation of Computing

CS12101
Module 01
Data Structure
Topics

● Data
● Data Type
● Introduction to Data Structure
● Data Structure – Need and Application
● Compile Time and Run Time
● typedef
● Memory Layout of C Program
● Pointer
● Dynamic Memory Allocation
● Concept of Linked List, Queue, and Stack
Data

Data can be defined as an elementary value or the collection of values,

for example, student's name and its id are the data about the student

Dr. Anand Kumar Mishra


Data Type

● A type of information transmitted between the programmer and the compiler

○ Programmer informs the compiler about

■ What type of data is to be stored?

■ How much space it requires in the memory?

Dr. Anand Kumar Mishra


Data Type

● Basic fundamental data types in C – int, char, float, and double


● Derived types – array, structure, union, and pointer
○ Array of integers, chars, floats, doubles, etc
○ Pointer is a variable
■ Stores the address of another variable of any data types
■ Allows for dynamic memory allocation in C
■ Help in passing variables by reference
■ Pointers cannot be added, multiplied, or divided
● However, we can subtract them
○ Structure that can contain variables of different data types [User-Defined Data Type]
○ Union store different data types in the same memory location [User-Defined Data Type]
● Enumeration (or enum) is a user-defined data type

Dr. Anand Kumar Mishra


Introduction of Data Structure
“a collection of data elements organized in a specific manner and functions is
defined to store, retrieve, delete and search for individual data elements”

● Organizing and storing data in computers


○ So that we can perform operations on the stored data more efficiently
● Arrays
● Linked Lists
● Stacks
● Queues
● Hash Tables
● Trees
● Heaps
● Graphs etc.
Dr. Anand Kumar Mishra
Data Structure

Primitive DS Non-Primitive DS

int, char, float, double, and


(Hold a single value) pointer
Linear data structure Non-Linear data structure

● Arrays ● Trees
● Linked Lists ● Graphs
● Stacks
● Queues
Types of Data Structure

● Linear data structure


a. elements are arranged in sequence one after the other
i. Array
ii. Stack
iii. Queue
iv. Linked List
● Non-linear data structure
a. elements in non-linear data structures are not in any sequence
b. arranged in a hierarchical manner
c. one element will be connected to one or more elements
i. Graph (vertex, edges)
ii. Trees (vertex, edges, only one edge between two vertices)

Dr. Anand Kumar Mishra


Non-linear data structure

● Graph Based Data Structures:


○ Spanning Tree and Minimum Spanning Tree
○ Strongly Connected Components
○ Adjacency Matrix
○ Adjacency List
● Tree based Data Structure
○ Binary Tree
○ Binary Search Tree
○ AVL Tree
○ B-Tree
○ B+ Tree
○ Red-Black Tree

Dr. Anand Kumar Mishra


Dr. Anand Kumar Mishra

Linear Vs Non-linear Data Structures


Linear Data Structures Non Linear Data Structures

The data items are arranged in sequential The data items are arranged in non-sequential
order, one after the other. order (hierarchical manner).

All the items are present on the single layer. The data items are present at different layers.

It can be traversed on a single run. That is, if It requires multiple runs. That is, if we start
we start from the first element, we can from the first element it might not be possible
traverse all the elements sequentially in a to traverse all the elements in a single pass.
single pass.

The memory utilization is not efficient. Different structures utilize memory in different
efficient ways depending on the need.

The time complexity increase with the data Time complexity remains the same.
size.

Example: Arrays, Stack, Queue Example: Tree, Graph, Map


Common operations that can be performed on the DS

● Searching: Search for any element in a DS


● Sorting: Sort the elements of a DS either in an ascending / descending order
● Insertion: Insert the new element in a DS
● Updation: Update the element, Replace the element with another element
● Deletion: Perform the delete operation to remove the element from the DS

Dr. Anand Kumar Mishra


Data Structure - Need

Applications are getting complexed and

Amount of data is increasing day by day

● Processor speed:
○ To handle very large amount of data, high speed processing is required, but as the data is
growing day by day to the billions of files per entity, processor may fail to deal with that much
amount of data
● Data Search:
○ Consider an inventory size of 106 items in a store, If our application needs to search for a
particular item, it needs to traverse 106 items every time, results in slowing down the search
process.

Dr. Anand Kumar Mishra


Data Structure - Need

● Multiple requests:
○ If thousands of users are searching the data simultaneously on a web server, then there are
the chances that a very large server can be failed during that process

In order to solve the above problems, “data structures are used”

Data is organized to form a data structure in such a way that -

all items are not required to be searched and required data can be
searched instantly

Dr. Anand Kumar Mishra


Data Structure - Need

● DS are used in every program or software system to arrange the data


● DS helps in the management of huge amounts of data such as,
○ a large integrated collection of databases
○ indexing services such as a hash table

● DS allows data/elements to be stored in a specific manner in the memory


● Efficient data search and retrieval
● DS organized the storage and retrieval of data and information (Main Memory
and Secondary Memory)

Dr. Anand Kumar Mishra


Data Structure - Need
● Efficiency:
If the choice of a data structure for implementing a particular ADT is proper, it makes the
program very efficient in terms of time and space
● Reusability:
The data structure provides reusability means that multiple client programs can use the data
structure
● Abstraction (invisibility):
The data structure specified by an ADT also provides the level of abstraction
The client cannot see the internal working of the data structure, so it does not have to worry
about the implementation part. The client can only see the interface

Dr. Anand Kumar Mishra


Data Structure - Application
Arrays Linked List

● Implementing stacks, queues, binary trees and graphs of


● Storing list of data elements belonging to predefined size
same data type ● Implement dynamic memory management functions of OS
● Polynomial implementation for mathematical operations
● Auxiliary storage for other data structures
● Circular linked list is used to implement OS or application
● Storage of binary tree elements of fixed functions that require round robin execution of tasks
count ● Circular linked list is used in a slide show where a user wants
to go back to the first slide after last slide is displayed.
● Storage of matrices ● When a user uses the alt+tab key combination to browse
through the opened application to select a desired application
● Doubly linked list is used in the implementation of forward and
backward buttons in a browser to move backwards and forward
in the opened pages of a website.
● Circular queue is used to maintain the playing sequence of
multiple players in a game.

Dr. Anand Kumar Mishra


Data Structure - Application
Stacks Queues
● Temporary storage structure for recursive
● It is used in breadth search operation in graphs.
operations
● Auxiliary storage structure for nested operations, ● Job scheduler operations of OS like a print buffer
function calls, deferred/postponed functions queue, keyboard buffer queue to store the keys
● Manage function calls pressed by users
● Evaluation of arithmetic expressions in various
programming languages ● Job scheduling, CPU scheduling, Disk Scheduling
● Conversion of infix expressions into postfix ● Priority queues are used in file downloading
expressions operations in a browser
● Checking syntax of expressions in a
● Data transfer between peripheral devices and
programming environment
● Matching of parentheses CPU.
● String reversal ● Interrupts generated by the user applications for
● In all the problems solutions based on CPU
backtracking.
● Used in depth first search in graph and tree ● Calls handled by the customers in BPO
traversal.
● Operating System functions
● UNDO and REDO functions in an editor
Dr. Anand Kumar Mishra
Data Structure - Application
Trees Graphs
● Implementing the hierarchical structures in ● Representing networks and routes in communication,
computer systems like directory and file system
transportation and travel applications
● Implementing the navigation structure of a
website ● Routes in GPS
● Code generation like Huffman’s code ● Interconnections in social networks and other
● Decision making in gaming applications network based applications
● Implementation of priority queues for priority ● Mapping applications
based OS scheduling functions
● Ecommerce applications to present user preferences
● Parsing of expressions and statements in
programming language compilers ● Utility networks to identify the problems posed to
● For storing data keys for DBMS for indexing municipal or local corporations
● Spanning trees for routing decisions in computer ● Resource utilization and availability in an organization
and communications networks ● Document link map of a website to display
● Hash trees
connectivity between pages through hyperlinks
● path-finding algorithm to implement in AI, robotics
and video games applications ● Robotic motion and neural networks

Dr. Anand Kumar Mishra


Compile Time & Run Time
Compile time vs Runtime

● Compile-time - The time at which the source code is converted into an


executable code
● Run time - The time at which the executable code is started running

Dr. Anand Kumar Mishra


Compile time vs Runtime

● Compile-time errors are the errors that occurred when we write the wrong
syntax
○ If we write the wrong syntax or semantics of any programming language, then the compile-
time errors will be thrown by the compiler
○ The compiler will not allow to run the program until all the errors are removed from the
program
○ When all the errors are removed from the program, then the compiler will generate the
executable file

Dr. Anand Kumar Mishra


Compile time vs Runtime

● Compile-time errors
○ Syntax error
■ When the programmer does not follow the syntax of any programming language, then
the compiler will throw the syntax error
■ int a, b:
○ Semantic errors
■ The semantic errors exist when the statements are not meaningful to the compiler
■ a+b=c;
● C programming language as it can contain only one variable on the left of the
assignment operator while right of the assignment operator can contain more than
one variable

Dr. Anand Kumar Mishra


Compile time vs Runtime

● Run-time errors
○ The runtime errors are the errors that occur during the execution and after compilation
■ Division by zero,
■ Determining the square root of a negative number, etc.
○ These errors are not easy to detect as the compiler does not point to these errors

Dr. Anand Kumar Mishra


typedef
typedef in C

● Keyword used in C programming to provide some meaningful names to the


already existing variable in the C program

typedef <existing_name> <alias_name>

typedef unsigned int unit;

unit a, b;

instead of writing:

unsigned int a, b;

Dr. Anand Kumar Mishra


Dr. Anand Kumar Mishra
struct student
{
char name[20];
int age;
};
struct student s1;
create the variable of student type by writing the following statement:

struct student s1;

Using, typedef

struct student OR typedef struct student


{ {
char name[20]; char name[20];
int age; int age;
}; } stud;
typedef struct student stud; stud s1,s2;
stud s1, s2;
Memory Layout of C Program
Memory Layout of C Program

● When we run any C-program, its executable image is loaded into RAM of
computer in an organized manner

Dr. Anand Kumar Mishra


Dr. Anand Kumar Mishra
Memory Layout of C Program (Process Address Space)

● Text Segment (Code Segment)


● Data Segment
○ Initialized Data Segment
■ Read-only area
■ Read-Write area
○ Uninitialized Data Segment (BSS Segment - Block Started by Symbol)
● Heap Segment
● Stack Segment
● Umapped or Reserved

Dr. Anand Kumar Mishra


Memory Layout of C Program
Stack Segment:
● It located at a higher address and grows and shrinks opposite to the heap
segment
● The stack contains local variables from functions and related book-keeping
data
● A stack frame will create in the stack when a function is called
● Each function has one stack frame
● Stack frames contain the function’s local variables arguments and return value.
● The stack contains a LIFO structure. Function variables are pushed onto the stack
when called and functions variables are popped off the stack when return.
● SP(stack pointer) register tracks the top of the stack.

Dr. Anand Kumar Mishra


Memory Layout of C Program

Heap Segment - It is used to allocate the memory at run time.

● Heap area managed by the memory management functions like malloc,


calloc, free, etc which may internally use the brk and sbrk system calls to
adjust its size.
● The Heap area is shared by all shared libraries and dynamically loaded
modules in a process.
● It grows and shrinks in the opposite direction of the stack

Dr. Anand Kumar Mishra


Memory Layout of C Program

Dr. Anand Kumar Mishra


Dr. Anand Kumar Mishra
Dr. Anand Kumar Mishra
Memory in C
Memory in C

● C has three different pools of memory.


○ static: global variable storage, permanent for the entire run of the program.
○ stack: local variable storage (automatic, continuous memory).
○ heap: dynamic storage (large pool of memory, not allocated in contiguous order)

Dr. Anand Kumar Mishra


Memory in C

● Static memory persists throughout the entire life of the program, and is usually
used to store things like global variables, or variables created with the static
clause. int theforce;
○ This variable uses 4 bytes of memory.
○ This memory can come from one of two places.
■ If a variable is declared outside of a function, it is considered global, meaning it is accessible
anywhere in the program. Global variables are static, and there is only one copy for the entire
program.
■ Inside a function the variable is allocated on the stack. It is also possible to force a variable to

be static using the static clause. static int theforce;

Dr. Anand Kumar Mishra


Memory in C
● The stack is used to store variables used on the inside of a function (including
the main() function).
● LIFO, “Last-In,-First-Out”
● Every time a function declares a new variable it is “pushed” onto the stack.
● Then when a function finishes running, all the variables associated with that
function on the stack are deleted, and the memory they use is freed up.
● The stack is a special region of memory, and automatically managed by the
CPU
○ so you don’t have to allocate or deallocate memory.
● Stack memory is divided into successive frames where each time a function is
called, it allocates itself a fresh stack frame.

Dr. Anand Kumar Mishra


Memory in C

● The heap is a large pool of memory that can be used dynamically


● This is memory that is not automatically managed
○ you have to explicitly allocate (using functions such as malloc), and deallocate (e.g. free) the
memory.
● Failure to free the memory when you are finished with it will result in what is
known as a memory leak – memory that is still “being used”, and not available
to other processes
● Heap memory requires you to use pointers

Dr. Anand Kumar Mishra


Pointer
Address of a Variable

int var; - variable, integer datatype

&var - address of the variable

Dr. Anand Kumar Mishra


Dr. Anand Kumar Mishra %p format specifier is used for printing the value of a pointer in C
Dr. Anand Kumar Mishra
Dr. Anand Kumar Mishra
Dr. Anand Kumar Mishra
Variable

● Variable that store data (values): int var; [normal variable]


● Variable that store address:int *var; [pointer variable]

Dr. Anand Kumar Mishra


Dr. Anand Kumar Mishra

Pointers

● Pointers (pointer variables) are special variables that are used to store
addresses rather than values.
● Lets declared a pointer p of int type

int* p; int *p1; int * p2;

we have declared a pointer p1 and a normal variable p2.

int* p1, p2;


Dr. Anand Kumar Mishra
● Value assigned to variable
● Address of variable
● Value assigned to variable
● Address of variable is stored in a pointer variable

Dr. Anand Kumar Mishra


● Value assigned to variable
● Address of variable is stored in a pointer variable
● Value assigned to variable

Dr. Anand Kumar Mishra


● Value assigned to variable
● Address of variable is stored in a normal variable

Dr. Anand Kumar Mishra


● Value assigned to variable
● Address of variable is stored in a normal variable

Warning

Dr. Anand Kumar Mishra


Warning-int-conversion

Dr. Anand Kumar Mishra


int* pc, c;

● a pointer variable pc and a normal variable c,


● both of type int
● pc and c are not initialized
● pointer pc points to either no address or a random address
● variable c has an address but contains random garbage value

c = 22;

● This assigns 22 to the variable c.


● That is, 22 is stored in the memory location of variable c

Dr. Anand Kumar Mishra


pc = &c;

● This assigns the address of variable c to the pointer pc.

c = 11; *pc = 2;

Dr. Anand Kumar Mishra


c = 11; *pc = 2;

Dr. Anand Kumar Mishra


Common mistakes when working with pointers
int c, *pc;
// pc is address but c is not
pc = c; // Error
// &c is address but *pc is not
*pc = &c; // Error
// both &c and pc are addresses
pc = &c; // Not an error
// both c and *pc are values
*pc = c; // Not an error

Dr. Anand Kumar Mishra


Common mistakes when working with pointers

#include <stdio.h>
int main() {
int c = 5;

int *p = &c;
printf("%d", *p);
return 0;
}

Dr. Anand Kumar Mishra


Understanding the size of
pointer

Dr. Anand Kumar Mishra


WHAT IS THE SIZE OF INT POINTER AND CHAR POINTER IN C?

● Pointer variable size is not depending on data type as pointer always stores the address of other variable

which is always integer data type.

● So, any pointer (int, char, double, etc) size will be 2 for 16 bit processor, 4 for 32 bit processor and 8 for 64

bit processor.

● sizeof() operator can be used to evaluate size of a variable/pointer in C.

Dr. Anand Kumar Mishra


● A pointer variable of type float holds only the address of floating point variable.

● A char pointer variable holds only the address of char type variable.

● But still the address of all these type of pointer variable is number.

○ Addresses are always numbers and it can’t be a character, a string or real/floating/double

numbers.

● Also note that addresses are unique.

● There can’t be 2 location in your computer's memory with same address.

Dr. Anand Kumar Mishra


64-based PC

Dr. Anand Kumar Mishra


Sizeof Pointer

Dr. Anand Kumar Mishra


C Program to convert hexadecimal to decimal number system:

Dr. Anand Kumar Mishra


C Program To Find Size of Pointer Variables

Dr. Anand Kumar Mishra


Dynamic Memory Allocation
Dynamic Memory Allocation

● An array is a collection of a fixed number of values


○ Once the size of an array is declared, you cannot change it

● Sometimes the size of the array you declared may be insufficient


● You can allocate memory manually during run-time
○ This is known as dynamic memory allocation in C programming
● One of the problems with dynamically allocated memory:
○ It is not destroyed by the compiler itself
■ that means it is the responsibility of the user to deallocate the allocated memory

Dr. Anand Kumar Mishra


Dynamic Memory Allocation

4 library functions provided by C defined under <stdlib.h> header file to facilitate


dynamic memory allocation in C programming. They are:

1. malloc() “malloc” or “memory allocation”


2. calloc()
3. free()
4. realloc()

Dr. Anand Kumar Mishra


DMA malloc
malloc for dynamic memory allocation

Syntax:

ptr = (castType*) malloc(size);

● The malloc function allocates space for an object whose size is specified by
size.
● The malloc() function reserves a block of memory of the specified
number of bytes. And, it returns a pointer of void which can be casted
into pointers of any form.
● If there is no space available, the malloc function return NULL.

Dr. Anand Kumar Mishra


Dr. Anand Kumar Mishra
Dr. Anand Kumar Mishra
Dr. Anand Kumar Mishra
Dr. Anand Kumar Mishra
Dr. Anand Kumar Mishra
Dr. Anand Kumar Mishra
Dr. Anand Kumar Mishra
Without CastType

Dr. Anand Kumar Mishra


Dr. Anand Kumar Mishra
Dr. Anand Kumar Mishra
Why is type casting needed in malloc?
The only reason for using a type-cast in malloc , would be to keep the source compatible with C++ because C++ does not allow type-
casting a void pointer to other type implicitly.

What is type casting in malloc?


The void pointer, or void*, is supported in ANSI C and C++ as a generic pointer type . A pointer to void can store an address to any
data type, and, in C, is automatically cast to any other pointer type on assignment, but it must be explicitly cast if dereferenced inline.

Is it necessary to typecast the address returned by malloc?


It is not necessary to typecast the address returned by malloc().

Dr. Anand Kumar Mishra


C++

Dr. Anand Kumar Mishra


C++

Dr. Anand Kumar Mishra


DMA calloc
calloc [contiguous allocation] for dynamic memory allocation
Syntax:

ptr = (castType*)calloc(n, size);


● The malloc() function allocates memory and leaves the memory uninitialized,
whereas the calloc() function allocates memory and initializes all bits to zero.
● The calloc function allocates space for an array of nmemb objects, each of whose
size is object_size.
● Space is initialized to all bits zero.
● The calloc function returns either a null pointer or a pointer to the allocated space.
Note: If you don’t want to initialize the allocated memory with zero, It would be better to
use malloc over calloc.

Dr. Anand Kumar Mishra


calloc [contiguous allocation] for dynamic memory allocation
ptr = (float*) calloc(25, sizeof(float));

The above statement allocates contiguous space in memory for 25 elements of


type float.

Dr. Anand Kumar Mishra


DMA realloc
realloc for dynamic memory allocation

Syntax:

ptr = realloc(ptr, x);

● The realloc function is different from the malloc and calloc, it deallocates the
old object and allocates again with the newly specified size.
● If the dynamically allocated memory is insufficient or more than required, you
can change the size of previously allocated memory using the realloc()
function.

Dr. Anand Kumar Mishra


realloc for dynamic memory allocation

● If piData is the null pointer, the realloc behaves like the malloc function.
● If piData not pointing a dynamically allocated memory, the behavior of realloc
is undefined.
● If piData is pointing a deallocated memory ( memory block has been
deallocated), the behavior of realloc is undefined.
● The return value of the realloc function is the pointer to a new object, or a null
pointer if the new object could not be allocated.

Dr. Anand Kumar Mishra


DMA free
free to deallocate the allocated memory

Syntax:

free(ptr);

● The free function is used to free the dynamically allocated memory.


● Dynamically allocated memory created with either calloc() or malloc()
doesn't get freed on their own. You must explicitly use free() to release the
space.

Dr. Anand Kumar Mishra


DMA Examples
Enter the number - calloc(), free()

Dr. Anand Kumar Mishra


Dr. Anand Kumar Mishra
Dr. Anand Kumar Mishra
Self-referential Structures
Self Referential Structures

● structures that have one or more pointers which point to the same type of
structure, as their member
● structures pointing to the same type of structures are self-referential in nature
● Self-referential structure plays a vital role in the linked list, trees, graphs, and
many more data structures
● In this type of structure, the object of the same structure points to the same data
structure and refers to the data types of the same structure.
● It can have one or more pointers pointing to the same type of structure as their
member.
Dr. Anand Kumar Mishra
In a linked list, the structure is used to store the data information and the address of the next node in the given
linked list.

Mainly the data part is of integer type, and the link address part is of pointer type, which holds the address of the
next node, so that it can for the Link ultimately.

Dr. Anand Kumar Mishra


Creating a random self-referential structure in the C programming language

struct node // Creating a node of structure type

int d1 ; // data 1 of integer type

int d2 ; // data 2 of integer type

struct node * link ; // Self referential structure link is pointing the same structure of the type node

};

int main()

struct node obj; // Creating an object of the node type, three parts one is data 1, data 2, and 3rd is of link type pointer

// carries the address of the next node.

Return 0 ;

Dr. Anand Kumar Mishra


Discussion about Data Type

● Integer data type


○ Store an integer value
○ Possible operations on an integer include
■ addition, subtraction, multiplication, modulo

● Abstract data type (ADT)


○ Concept or model of a data type [mathematical or logical concepts]
○ User knows what to do
■ without disclosing how to do it
○ Hides the inner structure and design of the data type
Linked List
Linked List

● A linear data structure


● A series of connected nodes
● Each node stores the data and the address of the next node
○ first node a special name called HEAD
○ last node in the linked list can be identified because its next portion points to NULL

Dr. Anand Kumar Mishra


Representation of Linked List

Each node consists:

● A data item
● An address of another node

Dr. Anand Kumar Mishra


Linked List Applications

● Dynamic memory allocation


● Implemented in stack and queue
● In undo functionality of softwares
● Hash tables, Graphs

Dr. Anand Kumar Mishra


Types of Linked List

● Singly Linked List


● Doubly Linked List
● Circular Linked List

Dr. Anand Kumar Mishra


Singly Linked List

● Each node has data and a pointer to the next node.

struct node {
int data;
struct node *next;
} Dr. Anand Kumar Mishra
Doubly Linked List

● We add a pointer to the previous node in a doubly-linked list


● We can go in either direction: forward or backward

struct node {
int data;
struct node *next;
struct node *prev;
} Dr. Anand Kumar Mishra
Circular Linked List

● A circular linked list is a variation of a linked list in which the last element is
linked to the first element
● This forms a circular loop

● It is used in multiplayer games to give a chance to each player to play the game.
● Multiple running applications can be placed in a circular linked list on an operating
system. The os keeps on iterating over these applications.
Dr. Anand Kumar Mishra
Representation of Linked List

● A data item
● An address of another node
struct node
{
int data;
struct node *next;
};
create a simple Linked List with three items

/* Initialize nodes */
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;
/* Allocate memory */
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
/* Assign data values */
one->data = 1;
two->data = 2;
three->data=3;
/* Connect nodes */
one->next = two;
two->next = three;
three->next = NULL;
/* Save address of first node in head */
head = one; Dr. Anand Kumar Mishra
Dr. Anand Kumar Mishra
Dr. Anand Kumar Mishra
Dr. Anand Kumar Mishra
Queue
Dr. Anand Kumar Mishra

Queue

● Linear data structure


● Principle: First In First Out (FIFO)
○ the item that goes in first is the item that comes out first
○ Example: To the ticket queue outside a cinema hall, where the first person entering the queue
is the first person who gets the ticket

● putting items in the queue is called enqueue


● removing items from the queue is called dequeue
Basic Operations of Queue

A queue is an object (an abstract data structure - ADT) that allows the following
operations:

● Enqueue: Add an element to the end of the queue


● Dequeue: Remove an element from the front of the queue
● IsEmpty: Check if the queue is empty
● IsFull: Check if the queue is full
● Peek: Get the value of the front of the queue without removing it

Dr. Anand Kumar Mishra


Dr. Anand Kumar Mishra

Working of Queue
● two pointers FRONT and REAR
● FRONT track the first element of the queue
● REAR track the last element of the queue
● initially, set value of FRONT and REAR to -1

Enqueue Operation Dequeue Operation

● check if the queue is full ● check if the queue is empty


● for the first element, set the value of ● return the value pointed by FRONT
FRONT to 0 ● increase the FRONT index by 1
● increase the REAR index by 1 ● for the last element, reset the values of
● add the new element in the position FRONT and REAR to -1
pointed to by REAR
Applications of Queue

● CPU scheduling, Disk Scheduling


● When data is transferred asynchronously between two processes.The queue
is used for synchronization. For example: IO Buffers, pipes, file IO, etc
● Handling of interrupts in real-time systems.
● Call Center phone systems use Queues to hold people calling them in order.

Dr. Anand Kumar Mishra


Stack
Stack

● Linear data structure


● Principle: Last In First Out (LIFO)
○ Last element inserted inside the stack is removed first
○ Example: Pile of plates on top of another
○ Put a new plate on top
○ Remove the top plate
● Putting an item on top of the stack is called push
● Removing an item is called pop

Dr. Anand Kumar Mishra


Stack

● Basic operations that allow us to perform different actions on a stack


○ Push: Add an element to the top of a stack
○ Pop: Remove an element from the top of a stack
○ IsEmpty: Check if the stack is empty
○ IsFull: Check if the stack is full
○ Peek: Get the value of the top element without removing it

Dr. Anand Kumar Mishra


Working of Stack Data Structure
The operations work as follows:

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.
4. On popping an element, we return the element pointed to by TOP and reduce its
value.
5. Before pushing, we check if the stack is already full
6. Before popping, we check if the stack is already empty

Dr. Anand Kumar Mishra


Applications of Stack Data Structure

● 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.

Dr. Anand Kumar Mishra

You might also like