0% found this document useful (0 votes)
22 views

unit-1

Data structures notes

Uploaded by

b2513621
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

unit-1

Data structures notes

Uploaded by

b2513621
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

1

DATA STRUCTURES
UNIT I
Concept of Abstract Data Types (ADTs)- Data Types, Data Structures, Storage Structures, and
File Structures, Primitive and Non-primitive Data Structures, Linear and Non-linear Data
Structures.
Linear Lists – ADT, Array and Linked representations, Pointers.
Arrays – ADT, Mappings, Representations, Sparse Matrices Linked Lists: Single Linked List,
Double Linked List, Circular Linked List , applications

Stacks: Definition, ADT, Array and Linked representations, Implementations and Applications
Queues: Definition, ADT, Array and Linked representations, Circular Queues, Dequeues,
Priority Queues, Implementations and Applications.

Data Structures
DATA STRUCTURES

UNIT – I

DATA STRUCTURES
DEFINITION
A data structure is a group of data elements that are put together
under one name and which defines a particular way of storing and
organizing data in a computer so that it can be used efficiently.
or
It is the way of organizing, storing, retrieving data and maintain
their relationship with each other.
or
It is the logical and mathematical model to organize and store
data in computer memory so that we can use it efficiently.

Characteristics of Data Structures


✓ It represents the logical representation of data in computer memory.
✓ It represents the logical relationship between the various data
elements.
✓ It helps in efficient manipulation of stored data elements.
✓ It allows the programs to process the data in an efficient manner.

Applications of Data Structures


Data structures are widely applied in the following areas:
✓ Compiler design
✓ Operating system
✓ Statistical analysis package
✓ DBMS
✓ Numerical analysis
✓ Simulation
✓ Artificial intelligence
✓ Graphics

1
2

Concept of Abstract Data Types (ADTs)

1. Define data structures. List various types of data structures. (OR)


Write short notes on Primitive and Non-primitive data structures.
Data may be organized in many different ways. The logical (or) mathematical model of a
particular organization of a data is called data structure. It is a collection of values and
possible operations.
Structural representation of data items, storage & retrieval operations efficiently.

Primitive Data Structures


 Primitive Data Structures are the basic data structures that directly operate upon
the machine instructions.
 Primitive data structures have different representations on different computers.
 Integers, Floating point numbers, Character constants, String constants and Pointers come
under this category.
 These data types are available in most programming languages as built in type.
o Integer: It is a data type which allows all values without fraction part. We can use it
for whole numbers.
o Float : It is a data type which use for storing fractional numbers.
o Character: It is a data type which is used for character values.
o Pointer : Pointer is a variable which holds memory address of another variable.

Non – Primitive data structures: Non-primitive data structures are more


shopisticated data structures.

Data Structures
3

 These are derived from primitive data structures. But extending the size and ranges of
basic data type
 They focus on grouping same or different data items with relationship between each
data item.
 Arrays, Lists and Files come under this category.
 Array: An array is a collection of memory locations which can share same data name
and same data type values.
 List: An order set containing variable number of elements is called as lists.
o The list is a sequential data structure.
o Lists are a way to store many different values under a single variable.
o Every item in this list is numbered with an index.
 File: A file is a collection of logically releated inforation. It can be viewed as large
list of records consisting of various fields.
 A Non- primitive data type is further divided into linear and Non- linear data
strucutre.
 Linera data stucture: A data structure is said to be linear if its elements form a
sequence or a linear list. Example: array, stacks, queues and linked lists come under
this category.
 Non- Linear data strucutres: A data structure is said to be non linear if its elements
form a hierarchical classification where, data items appear at various levels.Trees and
Graphs are widely used non-linear data structures.

Write a detail note on 1. ADT 2.Composite types 3. Primitive types

Data Type: Data type defines what type of value to stored on a variable.(or)A data type
defines a set of values and the allowable operations on those values. Different data types
include:
1. Abstract data types (ADT )
2. Composite types
3. Primitive types
Abstract data types (ADT ) : Abstract data types are mathematical models of
a set of data values or information that share similar behaviors. Abstract data
types are used in algorithms and also data items.(OR)
ADT is a user defined data type which encapsulates a range of data values and
their functions. (OR)

An abstract data type is a definition of new type, describes its properties and
operations.
Ex: ―Stack‖ is a ADT which contains push( ), pop( ) operations.
―Linked List‖ is a ADT which contains insert( ), delete( ) operations etc.
In an ADT, we encapsulate the data and the operations on data and we hide
them from the user.An abstract data type consists of

Data Structures
4

i) Declaration of data
ii) Declaration of operations
Advantages:
 Code is easier to understand.
 Implementations of ADTs can be changed without requiring changes to
the program that uses the ADTs.
 ADTs can be reused in future programs.
Composite types: Composite data type is any data type which can be
constructed in a program using the programming languages like primitive data
types and other data types.
Example : Structures, unions in ‗c‘.
struct Account
{
int account_number;
char first_name;
char last_name;
float balance;
};
Primitive types:
Primitive types are data types provided by a programming language. Primitive
types are also known as built-in types or basic types.
primitive types may include:
1. Character (character, char);
2. Integer (integer, int, short, long, byte) with a variety of precisions;
3. Floating-point number (float, double, real, double precision);
4. Boolean having the values true and false.
Basic primitive types :
SIZE NAME SIGNED INTEGER UNSIGNED
RANGE INTEGER RANGE
8 bits Byte -128 to + 127 0 to 255
16 bits Integer -32,768 to +32,767 0 to 65,535
-2,147,483,648
Double to
32 bits Long +2,147,483,648 0 to 4,294,967,295
integer
64 bits Long(JAV -9,223,372,036,854,775,808 0 to
A) to 18,446,744,073,709,551,
+9,223,372,036,854,775,808 615

Integer numbers
An integer number can hold a whole number, but no fraction. Integers may be
either signed (allowing Negative values) or unsigned (non negative values only).

Floating-point numbers

Data Structures
5

A floating-point number represents a real number that may have a fractional


part. These numbers are stored internally in scientific notation, they also called
decimal number. Floating point number contains integer, decimal point(.) and
exponent notation(‗e‘).
Examples of floating-point literals are: 20.0005 , 99.9 , −5000.12 , 6.02e23
Boolean: A boolean type is a single-bit type that can be either true (1) or false
(0).
Characters and strings: A character type (typically called "char") may contain
a single letter, digit, punctuation mark, or control character.Characters may be
combined into strings. The string data can include numbers and other
numerical symbols but will be treated as text.
Examples: ‘G‘ ‗M‘, "gminformatics" ,…
Write a details note on storage structures & Fie structures :
Storage Structures
The representation of a particular data structure in the memory of a computer
is called a storage structure. The storage structures are classified into:
1.Volatile storage(temporary)
2.Non-Volatile storage(parmanent)
Contents available even when power is switched off. includes secondary and
tertiary storage, as well as battery backed up main memory.
Storage Hierarchy

Cache memory: Fastest and most costly form of storage, volatile, managed by
the computer system hardware. Cache memory is an intermediate storage between
the CPU Registers and Main memory.It is small and fastest memory.CACHE memories
are accessed much faster than RAM.
Main memory: Main memory also called as primary memory. Primary memory is
the only type memory that is directly accessed by the CPU. Any data operated by the
CPU, is stored in primary memory. Contents of main memory are usually lost if a
power failure or system crash occurs.

Data Structures
6

Flash Memory:
Data can be written at a location only once, but location can be erased and
written to again.Can support only a limited number (10K – 1M) of write/erase
cycles.But writes are slow (few microseconds), erase is slower.
Optical storage
The Optical Drives are latest technology devices, that uses ―Light Sensors‖ to store the
information.The Light Sensors are called ―Lasers‖.Optical drives are most widely used
and reliable storage devices.The most popular optical storage devices are:
a) CD-ROM
b) DVD-ROM
c) CD-R
d) CD-RW
Magnetic Disk
Data is stored on spinning disk, and read/written magnetically.Primary
medium for the long-term storage of data.Data must be moved from disk to
main memory for access, and written back for storage.Direct access i.e.
possible to read data on disk in any order, unlike magnetic tape.
Magnetic Tapes
Hold large volumes of data and provide high transfer rates.Very slow access
time in comparison to magnetic disks and optical disks limited to sequential
access.Used mainly for backup, for storage of infrequently used information.
FILE STRUCTURES
A storage structure representation in auxiliary memory is often called a file
structure.A file is a collection of data stored on mass storage (e.g., disk or
tape).Advantages of mass storage
 Too big to fit in main memory
 Share data between programs
 Backup (disks and tapes are less volatile than main memory)
The data is subdivided into records. Each record contains a number of fields.
One or more field is the key field (e.g., address).
Files

Sequential Access Random Access

SEQUENTIAL ACCESS
A sequential file is one in which records can only be accessed one after another
from beginning to end. Records are stored one after another in auxiliary
storage, such as tape or disk, and there is an EOF (end-of-file) marker after the
last record. The operating system has no information about the record

Data Structures
7

addresses, it only knows where the whole file is stored. The only thing known
to the operating system is that the records are sequential.

Random access
If we need to access a specific record without having to retrieve all records
before it, we use a file structure that allows random access. Two file structures
allow this: indexed files and hashed files
INDEXED FILES
To access a record in a file randomly, we need to know the address of the
record.

HASHED FILES
A hashed file uses a mathematical function to accomplish this mapping. The
user gives the key, the function maps the key to the address and passes it to
the operating system, and the record is retrieved.

Data Structures
DATA STRUCTURES

Benefits / Advantages of ADT


✓ Modularity
✓ Reuse
✓ Code is easier to understand
✓ Implementation of ADT can be changed without requiring changes to
the program that uses ADT.

PRELIMINARIES OF ALGORITHMS
An algorithm is defined as a finite sequence of instructions each
of which has a clear meaning and can be performed with a finite
amount of effort in a finite amount of time.
✓ An algorithm is a method of finding solution in solving a problem.
✓ An algorithm is step by step procedure to solve a problem.
✓ Algorithms are used to find right solution to variety classification
problems.
✓ The algorithm word originated from the Arabic word “Algorism”
which is linked to the name of the Arabic mathematician AI
Khwarizmi.
✓ He is considered to be the first algorithm designer for adding
numbers.
✓ In algorithm all steps must unambiguous.

Structure of Algorithm
The structure contains the following steps:
✓ Input Step
✓ Assignment Step

5
DATA STRUCTURES

✓ Decision Step
✓ Repetitive Step
✓ Output Step

Algorithm for adding two numbers


Step1: Start
Step2: Read two numbers a, b
Step3: Compute result=a + b
Step4: Display the result
Step5: Stop

Algorithm for to check even or odd


Step1: Start
Step2: Read the value n
Step3: Compute if n modulo division by 2 is equal to 0 then goto step 4 &
then to step step 6 otherwise goto step 5
Step4: Display even number
Step5: Display odd number
Step6: Stop

Algorithm for to sum of n numbers


Step1: Start
Step2: Read the value n
Step3: Assign the value 1 to i and 0 to sum
Step4: Compute while i less than n then perform step5 and step6 then goto
Step4 otherwise goto Step7
Step5: compute sum=sum plus i
Step6: increment i
Step7: Display sum value
Step8: Stop

6
DATA STRUCTURES

Properties of Algorithms
✓ Finiteness: An algorithm must terminate after a finite number of
steps.
✓ Definiteness: The steps of the algorithm must be precisely defined or
unambiguously specified.
✓ Generality: An algorithm must be generic enough to solve all
problems of a particular class.
✓ Effectiveness: The operations of the algorithm must be effective such
that it must easily converted into machine code in a finite amount of
time.
✓ Input-Output: The algorithm must have zero, one or more inputs and
one or more outputs.

TIME AND SPACE COMPLEXITIES


✓ The performance of algorithm can be measured in terms of:
✓ Time
✓ Space
✓ The performance is the amount of memory needed and time required
to run it.
✓ We have two methods to determine the performance of the program.
✓ Analytical – in analysis
✓ Experimental – in measurement
✓ Time Complexity: The time complexity of an algorithm or a program
is the running time of the program as a function of input size.
✓ Space Complexity: The space complexity of an algorithm or program
is the amount of computer memory required for program execution as
a function of input size.

Analysis of Algorithms
✓ It is a technique to compare efficiency of different algorithms
✓ The speed of an algorithm can be different on different computers(time
taken will be different)

7
DATA STRUCTURES

✓ For solving a problem, the time is expressed in terms of


mathematical function of input size.
✓ Two algorithms are compared based on rate of growth of that
function
✓ If rate of growth is higher then the algorithm takes more time as
input size increases.
✓ The mathematical functions are represented by using asymptotic
notations
✓ It depends on how the program works efficiently.
✓ Efficiency means less space and less time required for execution.
✓ Hence time and space are the factors that determine the efficiency of
the program.
✓ We cannot compute time in terms of seconds for the execution of the
program because of several factors.
✓ Therefore we consider frequency count as time taken for execution of
the program.
✓ The frequency count is defined as the total number of times each
statement is being executed.

8
DATA STRUCTURES

Analyzing Algorithms
✓ Suppose “M” is an algorithm, and suppose “n” is the size of the input
data. Clearly the complexity f(n) of M increases as n increases.
✓ It is usually the rate of increase of f(n) with some standard functions.
✓ The most common computing times are
O(1), O(log2 n), O(n), O(n log2 n), O(n2), O(n3), O(2n)

9
DATA STRUCTURES

✓ When we have two algorithms to perform the same task and if first
one time complexity is O(n) and second one is O(n2) then we prefer
first one since as n increases the time required for execution of second
one is taking more time than the first one.
✓ Here we discuss about three cases for the efficiency of the algorithm.
✓ Best case – 1
✓ Worst case – n
✓ Average case – (n+1)/2
✓ It the algorithm takes minimum amount of time to run for its
completion then it is called best case time complexity
✓ It the algorithm takes maximum amount of time to run for its
completion then it is called worst case time complexity
✓ It the algorithm takes average amount of time to run for its completion
then it is called average case time complexity

10
8

Discuss about linear and Non linear data structures.

Linear data structures:


 A data structures is said to be linear, if its elements are connected in linear
fashion by means of logically or in sequence memory locations.
 A Linear data structure is a sequential representation of several data items
with one starting point and one ending point. That is a linear data structure
will have only one starting point and only one ending point.

 There are two ways to represent a linear data structure in memory,


o Static memory allocation
o Dynamic memory allocation
 The possible operations on the linear data structure are Traversal, Insertion,
Deletion, Sorting and Merging.
 Example of linear data structure One Dimensional Array, Linear Linked List,
Stack, Linear Queue.
 Array: An array is a collection of memory locations which can share same
data name and same data type values.
 Stack: Stack is a data structure in which insertion and deletion operations
on performed at one end only.
o The Insertion operation is refered to as ‗PUSH‘ and deletion oepration
is referred to as ‗POP‘ Operation.
o Stack is also called as Last in Fist Out( LIFO) data structure.
 Queue: The data structure which permits the insertion at one end and
deletion at another end, known as Queue.
o End at which deletion is occurs is known as FRONT end and another
end at which insertion occurs is known as REAR end.
o Queue is also called as First in First out data structure.
Non linear data structures:
 Non linear data structures are those data structure in which data items are
not arranged in a sequence.
 A non-linear data structure is a non-sequential representation of several
data items with several starting points and several ending points or no
definite starting and ending points.
 Example of non linear data structure are Hierarchical Structures, Circular
Structures, Topographical Structures tree and Graph.

Topographical Structures:

Diplom
a
Data Structures
9

Circular structure:

 Tree: a tree can be defined as finite set of data items(nodes) in which data
items are arranged in branches and sub branches according to requirement.
 Trees consist of nodes connected by edge, the node presented by circle and
edge lives connecting to circle.
 Graph: Graph is a collection of nodes (information) and connecting edges(
Logical relation) between nodes.
 A tree can be viewed as a restricted graph.
 Graphs have many types.
o Un- directed graph
o Directed graph
o Mixed graph
o Multi graph
o Simple graph
o Null graph
o Weighted graph

Diference between linear and Non linear data structures:


Linear Data structure Non Linear data structure
Every item is related to the previous Every item is attached with many
and time other items.
Data is arrange is linear sequence Data is not arranged in sequence
Data items can be traversed in a Data cannot be traversed in single run.
single run.
Eg. Array, stacks, linked list, queue Eg.tree, graph
Implementation is easy Implementation is difficult.

Data Structures
10

Arrays
Definition:
An array is a finite, ordered and collection of homogeneous data elements. An
array is finite because it contains only a limited number of elements, ordered
as all the elements are stored one by one in contiguous locations of the
computer memory in a linear order. As homogeneous all the elements of an
array are of the same data type.
Basic Terminology:
Size: The number of elements in an array is called the size or length of the
array.
Type: The type of an array represents the kind of data type .
Base: The base of an array is the address of the memory location where the
first element of the array is located.
Element − Each item stored in an array is called an element.
Index: All the elements in an array can be referenced by a subscript like A[i],
this subscript is known as index. The index value is always an integer value.
Range of Indices: Indices of arrays elements may range from a lower bound to
an upper bound called boundaries of an array.
Word: Word ‗w’ denotes the size of an element i.e., the amount memory that is
required to store an element of the array.

One-Dimensional arrays and their address mapping and operations


Definition:An array is a finite, ordered and collection of homogeneous data
elements. An array is finite because it contains only a limited number of
elements, ordered as all the elements are stored one by one in
contiguous/consecutive locations of the computer memory in a linear order. As
homogeneous all the elements of an array are of the same data type.

One-Dimensional Array:If only one subtype/index is required to refer an


element in an array, then the array is called as ―One-Dimensional Array‖.

Memory Allocation:All the indexed variables of an array are allocated


contiguous memory locations in computer‘s memory. So memory
representation of an array is simple. Suppose, we have an array with
n indexed variables, let the memory location of the first element is M.
If each element requires one word, then the location of any element
in the array can be calculated by using the following
formula.Address (A[i]) =M+(i x w)

Physical Representation

Eg: Let M=4560 and w=1,calculate the address of A[0], A[2], A[7]

Address (A[0]) = 4560+(0)x1 = 4560

Data Structures
11

Address (A[2]) = 4560 +(2)x1 = 4562

Address (A[7]) = 4560 +(7)x1 = 4567

Operations: Various operations that can be performed on an array are like


Traversing, Sorting, Searching, Insertion, Deletion and Merging.

Following operations can be performed on arrays:

Traversing: It is used to access each data item exactly once so that it can be
processed.
Searching: It is used to find out the location of the data item if it exists in the
given collection of data items.
Insertion: It is used to add a new data item in the given collection of data
items.
Deletion: It is used to delete an existing data item from the given collection of
data items.
Sorting: It is used to arrange the data items in some order i.e. in ascending or
descending order in case of numerical data and in dictionary order in case of
alphanumeric data.
Merging: It is used to combine the data items of two sorted files into single file
in the sorted.
Multi-Dimensional arrays and their address mapping and operations
Definition:An array is a finite, ordered and collection of homogeneous data
elements. An array is finite because it contains only a limited number of
elements, ordered as all the elements are stored one by one in contiguous
locations of the computer memory in a linear order. As homogeneous all the
elements of an array are of the same data type.

Multi-Dimensional Array:If elements are represented using more than one


index/subscript, then the array is called as ―Multi-Dimensional Array‖. Two
dimensional arrays are a collection of homogeneous elements in which
elements are ordered in rows and columns.

Eg: Consider an array of size mxn, here m is the no.of rows and n is the no.of
columns as follows.

a11 a12 a13 . . . . a1n


a21 a22 a23 . . . . a2n mXn
. . . ……………………
....
am1 am2 am3 . . . .
amn

Data Structures
12

Memory Representation: Like one-dimensional arrays, two-dimensional


arrays are also stored in contiguous memory locations. There are two
conventions of storing two-dimensional array elements in the memory.

1. Row-Major Order

2. Column-Major Order

Row-Major Order:The elements of a two-dimensional array are stored in row-


by-row basis, that is all the elements in the first row, then in the second row
and so on.

Column-Major Order:The elements of a two-dimensional array are stored in


column-by-column basis, that is all the elements in the first column are stored
in their order of rows, then in the second column and so on.

Eg:
a11 a12 a13
a21 a22 a23
a31 a32 a33
3X3

Memory Representation

Referencing an element: To refer an element in a two-dimensional structure,


we need two index values one for row another for column. The indexing formula
of row-major order is different from columnmajor order.Let us assume that we
have an array with mxn elements.

Row-Major Order:

Address(aij) = (i-1)xn+j

Eg: Address(a32) = ((3-1)x3)+2 = 2x3+2 = 8

If the base address is M, then the above formula can be modified as follows.

Data Structures
13

Address(aij) = M+(i-1)xn+j-1

Eg: Address(a32) = 4560+((3-1)x3)+2-1

= 4560+2x3+2-1

=4560+6+2-1 = 4567

Column-Major Order:

Address(aij) = (j-1)xm+j

Eg: Address(a32) = ((2-1)x3)+2 = 2x3+2 = 6

If the base address is M, then the above formula can be modified as follows.

Address(aij) = M+(j-1)xm+i-1

Eg: Address(a32) = 4560+((2-1)x3)+3-1

= 4560+3+3-1

=4560+3+2 = 4565

Sparse Matrix and representation of Sparse Matrix

A sparse matrix is a two – dimensional array where the majority of the elements have
the value null.

Input : An array a with two- Another array spm with two multiplied by 3.`

Output : Representation of Sparse Matrix in a Triplet Form.

SparseMatrix:Two columns mxn . There may be situation in ins Non-Zero values.


Such matrix is non-zero values, that is majority of values non-zero values. So, to
represent those 6 values, we are we can represent the sparse matrix by using Triplet -
dimensions containing elements, most of the elements are zeros two-dimensions
whose size is equal to no.of non-dimensional array.

The above matrix contains 5 rows and 6 columns. Then the total number of
elements are 5x6=30. If each element requires 4 Bytes of memory, then we
need totally 120 Bytes of memory. But if we observe the matrix, it has very few
non-zero values, that is majority of values are zeros. We have only 6 non-zero

Data Structures
14

values. So, to represent those 6 values, we are wasting 120-(6x4) = 120-24 = 96


Bytes of memory. (6x4) = 120-24 = 96 Bytes of memory.

An array a with two-dimensions containing elements, most of the elements are


zeros Another array spm with two-dimensions whose size is equal to no.of non-
null values multiplied by 3. Representation of Sparse Matrix in a Triplet Form.

Sparse matrices are used by scientists and engineers when solving partial
differential equations. For example, a measurement of a matrix's sparsity can
be useful when developing theories about the connectivity of
computer networks. When using large sparse matrices in a computer program,
it is important to optimize the data structures and algorithms to take
advantage of the fact that most of the values will be zero.

Data Structures
15

Discuss about the list implementation concepts.

Linked List is a linear data structure and it is very common data structure
which consists of group of nodes in a sequence which is divided in two
parts.Each node consists of its own data and the address of the next node and
forms a chain.Linked Lists are used to create trees and graphs.

Advantages of Linked Lists


 They are a dynamic in nature which allocates the memory when
required.
 Insertion and deletion operations can be easily implemented.
 Stacks and queues can be easily executed.
 Linked List reduces the access time.
Disadvantages of Linked Lists
 The memory is wasted as pointers require extra memory for storage.
 No element can be accessed randomly.
 it has to access each node sequentially.
 Reverse Traversing is difficult in linked list.

Applications of Linked Lists


 Memory management: linked list are useful in managing memory as
dynamic i.e., DMA.
 Polynomial manipulations: the operations on polynomial such as
addition, subtraction,multiplication etc are easily implemented using
linked lists.
 Insertions and deletions in graphs of data: the insertions and
deletions are efficiently performed when linked lists are used to maintain
the group of data.
 Linked lists are used to implement stacks, queues, graphs, etc.
 Linked lists let you insert elements at the beginning and end of the list.
 In Linked Lists we don‘t need to know the size in advance.

Data Structures
16

Types of Linked Lists

Singly Linked List : Singly linked lists contain nodes which have a data part
as well as an address part i.e. next, which points to the next node in sequence
of nodes. The operations we can perform on singly linked lists are insertion,
deletion and traversal.

Doubly Linked List : In a doubly linked list, each node contains two links the
first link points to the previous node and the next link points to the next node
in the sequence.

Circular Linked List : In the circular linked list the last node of the list
contains the address of the first node and forms a circular chain.

Data Structures
17

Linked List & Single Linked Linear List

A linked list is an ordered collection of finite, homogeneous data elements


called nodes. Unlike arrays, linked lists are dynamic structures as nodes are
created whenever we require. The amount of memory required can be varied
during its use. In Linked Lists, the adjacency is maintained by using links or
pointers. A link or pointer is the address of the subsequent(next/previous)
element in the list. So, we need to maintain both data and link in a node. Thus,
a node consists of two parts Data and Link.Data part of a node holds the user's
data and Link part of the node holds the address value of its next/previous
node in the list. Link

DATA Link to the next node

Single Linked List: In single linked list, each node contains only one link
which points to the next node in the list. We maintain a pointer called Headptr
to point the very first node of the list.

In the above example, we have five nodes from N1 to N5. The first node is called
as Head Node and last node is called as Tail Node. First node points to second,
second points to third and so on. Tail Node always points to null which
indicates there no more node in the list. In single-linked list, we can travel only
in direction that is from Head Node to Tail Node. We can move only to the next
node not to the previous node of the list. That is why it is called as one way list.

Operations:

addNewNode (data): This operation adds a new node to the list with the given
data.

delete (index): This operation deletes an existing node from the list at given
index position.

size(): This operation gives the size i.e., how many nodes are there in the list.

insert (index, data):This operation inserts a new node to the list at a given
index position with a given data value.

traversal():This operation gathers data from each node in the list starting from
head to tail node and displays the data.

Data Structures
18

Define linked list. Explain how to insert and delete an element at the
beginnning of the list.

Linked List is a linear data structure and it is very common data structure
which consists of group of nodes in a sequence which is divided in two parts.

Each node consists of its own data and the address of the next node and forms
a chain.Linked Lists are used to create trees and graphs.

Insertion: : Insertion is used to add a new data item. A node can be inserted
in various positions.
i. Inserting at the front ( as a first element)
ii. Inserting at end ( as a last element)
iii. Inserting at any position.
Steps for inserting an element in the beginning of a list
1. Create a new node
2. Make the next part of new node point to the first node
3. Make the START pointer point to new node
Algorithm

new_nodenext=START;

START =new_node;

Data Structures
19

Steps for inserting an element in the end


1. Create a new node
2. Make the next of new node point to NULL
3. Make the previous node point to new node.
Algorithm for Insert a node at the end of a single linked list:

while(pnext!=NULL)
{
p=pnext;
}
pnext=new_node;
new_nodenext=NULL;

Steps for inserting an element in the middle


1. Create a new node
2. Make the next part of new node point to the next of previous node
3. Make the previous node point to new node

Algorithm for Insert a node at the middle of a single linked list:

while(p!=insert_position)
{
P=pnext;
}
store_next=pnext;
pnext=new_node;
new_nodenext=store_next;

Data Structures
20

Deleting a node from a list: It is used to delete an existing data item from the
given collection of data items. There three ways to delete element.

i. Deleting from the front of the list


ii. Deleting from the end of the list
iii. Deleting from any position in the list

Steps for deleting a node in the beginning


1. Store the node to be deleted in a temporary pointer
2. Make START point to next node in the list
3. Delete the node pointed by temporary pointer

Steps for deleting a node from the middle / end


1. Store the node to be deleted in a temporary pointer
2. Make the previous node‘s next point to the next of the node that is being deleted
3. Delete the node pointed by temporary pointer

Steps for deleting a node from the middle / end

1. Store the node to be deleted in a temporary pointer


2. Make the previous node’s next point to the next of the node that is being deleted
3. Delete the node pointed by temporary pointer

Data Structures
21
B.Sc. IV SEMESTER

Algorithm for deleting a node in single linked list

node *delete(node *head, char d)


{
node *p, *q;
q=head;
p=headnext;
if(qdata==d) //start node
{
head=p;
delete(q);
}
else //internal node
while(pdata!=d) Last node
{
p=pnext;
q=qnext;
}
if(pnext==NULL)
{
qnext=NULL;
delete(p);
}
else
{
qnext=p—next;
delete (p);
}
return head;
}

Data Structures
22

Discuss about Double Linked Linear List

A linked list is an ordered collection of finite, homogeneous data elements


called nodes. Unlike arrays, linked lists are dynamic structures as nodes are
created whenever we require. The amount of memory required can be varied
during its use.

In Linked Lists, the adjacency is maintained by using links or pointers. A link


or pointer is the address of the subsequent(next/previous) element in the list.
So, we need to maintain both data and link in a node. Thus, a node consists of
two parts Data and Link. Data part of a node holds the user's data and Link
part of the node holds the address value of its next/previous node in the list.

Double Linked List:


In double linked list, each node contains two links one points to the next node
another points to the previous node in the list. We maintain a pointer called
Headptr to point the very first node of the list.

Example:

In the above example, we have four nodes from N1 to N4. The first node is
called as Head Node and last node is called as Tail Node. First node points to
second, second points to third and so on. The left link of head node and right
link of tail node points to null. It indicates that there is no previous node to
head and no next node to tail node. In double-linked list, we can travel in
either directions that is from Head Node to Tail Node and Tail Node to Head
Node. That is why it is called as two-way list.

Memory Organization Of A Doubly Linked List

Data Structures
23

Operations:
addNewNode (data):This operation adds a new node to the list with the given
data.
delete (index):This operation deletes an existing node from the list at given
index position.
size():This operation gives the size i.e., how many nodes are there in the list.
insert (index, data):This operation inserts a new node to the list at a given
index position with a given data value.
traversal():This operation gathers data from each node in the list starting from
head to tail node and displays the data.
Define double linked list. Explain how to insert and delete an element at
the end of the list.
In double linked list, each node contains two links one points to the next node
another points to the previous node in the list. We maintain a pointer called
Headptr to point the very first node of the list.
Steps for inserting in the beginning of a doubly linked list
1. Create a new node
2. Make the next part of new node equal to START
3. Make the previous part of new node equal to NULL
4. Make the previous part of the node pointed by START to new node
5. Make START point to new node
Algorithm for insert a node at the start
new_nodenext=head;
headprev=new_node;
new_nodeprev=NULL;
head=new_node;

Steps for inserting an element in the middle of a doubly linked list


1. Create a new node
2. Make the next part of new node equal to next part of the previous node
3. Make the previous part of new node equal to previous part of next node
4. Make the next part of previous node point to new node
5. Make the previous part of next node point to new node

Data Structures
24

Algorithm for insert internal node.


while(p!=insert_position)
{
p=pnext
}
store_next=pnext
pnext=new_node;
new_nodenext=store_next;
store_nextprev=new_node;

Steps for inserting an element at the end of a doubly linked list


1. Create a new node
2. Make the next part of the new node equal to NULL
3. Make the previous part of the new node equal to TAIL
4. Make the next part of the previous node equal to new node
5. Make TAIL equal to new node
Algorithm:
while(pnext!=NULL)
{
p=pnext;
}
pnext=new_node;
new_nodeprev=p;
new_nodenext=NULL;

Data Structures
25

Deleting an element from a doubly linked list


Deleting a node from a list is as simple as changing the links. Hence deleting a
node from a list is much faster when compared to arrays. Like insertion the
deletion logic also varies depending on from where in the list we are going to
delete the node.

1. Deletion at beginnning

2. Deletion at middle

3. Deletion at end

Deletion in the beginning of a doubly linked list


1. Make the temporary pointer point to the node to be deleted
2. Make the START point to the next node of START
3. Make the previous of the next node equal to previous of the node to be deleted
4. Delete the node pointed to by temporary pointer.

Algorithm:

p=head;

head=headnext;

headprev=NULL;

delete(p);

Deletion in the middle of a doubly linked list


1. Make the temporary pointer point to the node to be deleted
2. Make the next part of the previous node equal to next of the node to be deleted
3. Make the previous part of the next node equal to previous part of the node to be
deleted
4. Delete the node pointed to by temporary pointer
Algorithm:
While(p!=delete_position)
{

Data Structures
26

P=pnext;
}
store_next=pnext;
store_prev=pprev;
store_nextprev=store_prev;
store_prevnext=store_next;
delete(p);

Deletion at the end of a doubly linked list


1. Make the temporary pointer point to the node to be deleted

2. Make the next part of the previous node equal to next of the node to be deleted

3. Make the TAIL equal to the previous part of the node to be deleted

4. Delete the node pointed to by temporary pointer.

Algorithm:

store_prev=pprev;

store_prevnext=NULL;

delete(p);

Data Structures
27

Write a detiled note on Circular Linked List .

A linked list is an ordered collection of finite, homogeneous data elements


called nodes.Unlike arrays, linked lists are dynamic structures as nodes are
created whenever we require. The amount of memory required can be varied
during its use. In Linked Lists, the adjacency is maintained by using links or
pointers. A link or pointer is the address of the subsequent(next) element in the
list. So, we need to maintain both data and link in a node. Thus, a node
consists of two parts Data and Link. Data part of a node holds the user's data
and Link part of the node holds the address value of its next/previous node in
the list.

CircularLinked List: A linked list where the last node points the header node
is called the ‗Circular Linked List‘. A circular list doesn't have definite head and
definite tail nodes. Any Node in the list can be chosen as Head and node before
that as Tail. If there are more than one Node in the list, then every Node will
have next Node. If there is only one Node in the list that itself is the head and
tail. The tail Node in the circular list points to the head Node.

Operations:
addNewNode (data):This operation adds a new node to the list with the given data.
delete (index):This operation deletes an existing node from the list at given index
position.
size():This operation gives the size i.e., how many nodes are there in the list.
insert (index, data):This operation inserts a new node to the list at a given index
position with a givendata value.
traversal():This operation gathers data from each node in the list starting from head to
tail node and displays the data.

Data Structures
28

Differences between single linked list and double linked list

SINGLE LINKED LIST DOUBLE LINKED LIST

1.In SLL the list will be traversed in 1. In DLL the list will be traversed in
only one way i.e., in forward two ways either in forward (or)
direction. Backward directions.

2.In SLL the node contains only one 2. In DLL each node contains two Link
link field. fields.

3.The conceptual view (a logical 3. The conceptual view (a logical


organisation) of SLL is: organization) of a DLL is:

4.Every node contains the address of 4. Every node contains the address of
next node. next node as well as the address of the
previous node.

5.The node structure of DLL is as


5.The node structure SLL is as follows:
follows

6.In SLL the first node address is 6. In DLL the first node address is
stored in a special pointer variable stored in ―left end‖ and last node
―START‖. address is stored in ―right end‖ pointer
variables.

7. Three linear arrays are required to


7.Two linear arrays are required to represent a double linked list in
represent a single linked list in memory.
memory.

Data Structures
29

What is stack? Explain its Applications


A Stack is a linear list in which insertions and deletions take place at the same
end. The end through which items are added and deleted is called the Top End.
The other end of the list is called the Bottom End.

 A stack is a last-in-first-out ( LIFO ) structure.


 Insertion operation is referred as ―PUSH‖ and deletion operation is
referred as ―POP‖.
 The most accessible element in the stack is the element at the position
―TOP‖.

We can implement the stack ADT either with array or linked list.

 Stack overflow happens when we try to push one more item onto our stack than
it can actually hold.
 Stack underflow happens when we try to pop (remove) an item from the stack,
when nothing is actually there to remove.
 To use a stack efficiently, we need to check the status of stack as well. For
the same purpose, the following functionality is added to stacks –
o peek() − get the top data element of the stack, without removing it.
o isFull() − check if stack is full.
o isEmpty() − check if stack is empty.
Applications of stack:
 Paranthesis matching: Stacks can be used to find out whether the given
equation is balanced or not. It mainly checks for the matching of left and
right parenthesis in an equation.
Example:
(A+B(x+y)+C is not a valid expression because it miss right paranthesis
(A+B(x+y)+C) is a valid expression
 Convert from infix to postfix: Stacks are used to convert an infix to
postfix expression.

Data Structures
30

Infix expression: (a+b)*c


Postfix expression : ab+c*
Prefix expression: *+abc
 To evaluate postfix forms: To evaluate postfix expression, stacks can be
used. While evaluating, operands are stored onto a stack and popped
when an operator occurs.
The postfix expression ―2 3 *6 +‖ get executed as ―12‖
 Recusrsion: Recursive functions are implemented using stacks. The
copies of variables at each level of recursion are stored in stack.
Example
Fact(3)=3*fact(2)
= 3*2*Fact(1)
= 3*2*1
= 3*2
=6
 Comuter applications that use undo feature: undo is cancel the
previous action. To rememeber these in LIFO order computer
applications use stack.
 Compilers use stacks in syntax analysis phase to check whether a
particular statement in a program is syntactically correct or not.
 Computers use stack during interrupts and function calls. The
information regarding actual parameters return values, return addresses
and machine status is stored in stack.
 Stacks are used in tree traversal techniques
 Stacks are used in depth first search of a graph.
 Keeping track of function calls: To keep track of function calls, stack
can be used to return to the point where it is called after executing the
function. When a function is called the control transfers to the function
and executes all the statements there. But, to return to the pointer where
it is called a stack is used to remember the address of the calling
statement.

Main()
{
fun();
…………
…………
}
fun()
{
………..

Data Structures
31

What is stack ? Explain basic operations of stack data structures.


A Stack is a linear list in which insertions and deletions take place at the same
end. The end through which items are added and deleted is called the Top End.
The other end of the list is called the Bottom End.
Basic Operations
Stack operations may involve initializing the stack, using it and then de-
initializing it. Apart from these, a stack is used for the following two primary
operations.
push( ) − Pushing (storing) an element on the stack.

pop( ) − Removing (accessing) an element from the stack.

When data is PUSHed onto stack, To use a stack efficiently, we need to check
the status of stack as well. For the same purpose, the following functionality is
added to stacks.

peek( ) − get the top data element of the stack, without removing it.

isFull( ) − check if stack is full.

isEmpty( ) − check if stack is empty.

Stack is said to be in Overflow state when it is completely full and is said to be


in Underflow state if it is completely empty.
Push Operation
The process of putting a new data element onto stack is known as a Push
Operation. Push operation involves a series of steps.
Step 1 − Checks if the stack is full.
Step 2 − If the stack is full, produces an error and exit.
Step 3 − If the stack is not full, increments top to point next empty space.
Step 4 − Adds data element to the stack location, where top is pointing.
Step 5 − Returns success.
Algorithm for Push operation
1. Begin procedure push: stack, data

2. if stack is full return null end if

3. top = top + 1

4. stack[top] = data

5. end procedure

Data Structures
32

Pop Operation
Accessing the content while removing it from the stack, is known as a POP
Operation. A POP operation may involve the following steps.
Step 1 − Checks if the stack is empty.
Step 2 − If the stack is empty, produces an error and exit.
Step 3 − If the stack is not empty, accesses the data element at which top is
pointing.
Step 4 − Decreases the value of top by 1.
Step 5 − Returns success.
Algorithm for Pop operation
1. begin procedure pop: stack
2. if stack is empty return null
3. end if 4. data = stack[top]
5. top = top - 1
6. return data
7. end procedure

Peek( ):
This operation returns the most accessible element from stack.

begin procedure peek

Data Structures
33

return stack[top]

end procedure

isFull( ):
This operation is performed to know whether the stack is full or not. If the TOP
value reaches to MAXSIZE then the stack is full.

begin procedure isfull


if top equals to MAXSIZE
return true
else
return false
endif
end procedure
isEmpty( )
This operation is used to check whether the stack is empty or not begin
procedure isempty.
if top less than 1
return true
else
return false
endif
end procedure

What is stack? Discuss about aray and linked representation of a stack.


A Stack is a linear list in which insertions and deletions take place at the same
end. The end through which items are added and deleted is called the Top End.
The other end of the list is called the Bottom End.The two basic operations
associated with stacks are:
Push: is the term used to insert an element into a stack.
Pop: is the term used to delete an element from a stack.
A stack may be represented in the memory in various ways. Mainly there are
two ways. They are:
1. Using one dimensional arrays(Static Implementation)
2. Using linked lists(Dynamic Implementation)
Stack Representation using Arrays :
A Stack data structure can be represented using arrays. We perform stack
operations Push and POP by maintaining the top value to point to the topmost
element position of the stack.

Data Structures
34

Abstract Class :

AbstractDataType Stack
{
Instances
Linear list of elements: one end is called the bottom the other is the top.
Operations
isEmpty() : Return True if stack is empty, return False otherwise.
isFull() : Return True if stack is full, return False otherwise
push(x) : Add element x to the stack
pop(x) : Delete top element from stack and put it in x.
}

Operations:
push(x) : Adding items to the stack is called as Push operation. Here x is the
data item that is being added onto the stack.

Data Structures
35

pop(x) : Deleting items from the stack is called as Pop operation. Here x is the
data item that is being deleted from the stack.
isFull( ) :This function verifies whether the stack is full or not. If stack is full, it
returns true, otherwise return false.
isEmpty(): This function verifies whether the stack is empty or not. If stack is
empty, it returns true, otherwise it returns false.
Algorithm
Stack Operations: Basically, there are two operations performed on the
stack.
Push: Push is the term used to insert the element on the top of stack.
Pop: Pop is the term used to delete the elements from top of the stack.
Algorithm: push(s, top, x):[This algorithm inserts the elements.]
Step: 1 [check for the stack over flow]
If (top > = max-1) then write (―stack over flow‖)
Return;
Step: 2 [increment top by 1]
top top+1;
Step: 3 [insert element]
s[top] x;
Step: 4 [finished]
Return;
Algorithm pop(s, top): [this algorithm deletes the top element from the stack]
Step: 1 [check for the stack under flow]
if (top= = -1) then write (―stack underflow‖)
Return;
Step: 2 [assign top element to x]
X s[top];
Step: 3 [decrement top by 1]
top top-1;
Step: 4 [finished]
Return;
Algorithm isEmpty(s, top): [this algorithm checks the stack is empty ]
Step: 1 [check for the stack is empty()]
if (top= = -1) then write (―stack Empty‖)
Step: 2.[finished]
Return;
Algorithm: isFull(s, top):[This algorithm checks the stack is full]
Step: 1 [check for the stack is full]
If (top > = max-1) then write (―stack is Full‖)
Step: 2 [finished]
Return;
Stack Representation using Linked List:
Array representation of stacks is very easy, but it allows only fixed sized stacks.
In several applications, the size of the stack may vary during program
execution. In such cases we may use linked list. A single linked list structure is

Data Structures
36

sufficient to represent to any stack. Here data field is users data and link field
is as usual point to next item.
We can use either single linked or double linked list to represent a stack data
structure. But it is easy to use single linked list to represent a stack data
structure.

Example :

In the linked list representation, first node on the list is the current item that is
the item at the top of the stack and the last node is the node containing bottom
most item. So PUSH operation will perform at the front and POP operation will
perform at front. SIZE of the stack is not important here because dynamic
representation.

The implementation of isFull() method is not necessary because the only way to
know whether we can add an element on to the stack or not is to see whether
enough space exists to create a node of type Node. This check can be done by
invoking new.
Abstraction of Stack:
Data Objects:
Node :-consisting of two parts data and address.
headptr :-always points to the address of first node in the list
next :- used to store next node address
Methods :
isEmpty(): This method verifies that the stack is empty or not. If the stack is
empty it returns true, otherwise it returns false.
push(x): This method adds a data item x onto the stack. If the operation
executed successfully it returns true, otherwise it returns false.

Data Structures
37

pop(x): This method pops a data item from the stack and places it in x. If the
operation executed successfully it returns true, otherwise it returns
false.
peek(): To access the top element of the stack without removing it.

Algorithms
Algorithm: push_LL (s, top, x):[This algorithm inserts the elements.]
Step: 1[Create new node ]
New=Getnew(Node);
Step: 2 [inserting Values]
New Data=Item
Step3: [palcing reference]
New link=top
Top=new
Step: 4 [top is assigns to stack head]
Stack_Headlink=top
Step:5 [Finish]
Return;
Algorithm pop_LL(s, top): [this algorithm deletes the top element from the
stack]
Step: 1 [check for the stack under flow]
PTR= Stack_Headlink;
if (PTR=NULL) then write (―stack underflow‖)
Return;
Step: 2 [assign top element to x]
X PTR[top]; [Display x]
Step: 3 [Assign top to next node]
top = ptr link;
Step: 4[Assign head_ptr to top]
Stack_Head=top;
Step: 5 [finished]
Return;
Algorithm isEmpty(s, top): [this algorithm checks the stack is empty ]
Step: 1 [check for the stack is empty()]
if (top= = null) then write (―stack Empty‖)
Step: 2.[finished]
Return;

Data Structures
38

What is an arithmetic expression? Explain their notations?


An algebraic expression is a legal combination of operators and operands.
Operand may be a variable like x, y, z or a constant like 5, 4, 6 etc. Operator is
a symbol which signifies a mathematical or logical operation between the
operands. Examples of familiar operators include +, -, *, /, ^ etc. An algebraic
expression can be represented using three different notations. They are infix,
postfix and prefix notations:

Infix: It is the form of an arithmetic expression in which we fix (place) the


arithmetic operator in between the two operands.

Example: (A + B) * (C - D)

Prefix: It is the form of an arithmetic notation in which we fix (place) the


arithmetic operator before (pre) its two operands. The prefix notation is called as
polish notation

Example: * + A B – C D

Postfix: It is the form of an arithmetic expression in which we fix (place) the


arithmetic operator after (post) its two operands. The postfix notation is called
as suffix notation and is also referred to reverse polish notation.

Example: A B + C D - *

The three important features of postfix expression are:

 The operands maintain the same order as in the equivalent infix


expression.
 The parentheses are not needed to designate the expression
unambiguously.
 While evaluating the postfix expression the priority of the operators is no
longer relevant.

Data Structures
39

Convert the following infix expression A + B * C – D / E * H into its equivalent


postfix expression.

Convert ((A – (B + C)) * D) ↑ (E + F) infix expression to postfix form:

Data Structures
40

What is a Queue ? Explain its operations?

A queue is a leaner list, which has two ends, where items are inserted at one end
called the rear and deleted at the other end called the front. Another name for a queue
is a ―FIFO‖ or ―First-in-first-out‖ list. 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). We can implement the queue by using Arrays and linked list.

Arrays

Linked list representation

Queue operations :
Enqueue:
The process of adding an element into the queue is known as Enqueue. The
following steps are perform queue operations.

Step 1 − Check if the queue is full.


Step 2 − If the queue is full, produce overflow error and exit.
Step 3 − If the queue is not full, increment rear pointer to point the next empty space.
Step 4 − Add data element to the queue location, where the rear is pointing.
Step 5 − Return success
Procedure enqueue(data)
if queue is full
return overflow
end if
rear = rear + 1
queue[rear] = data
return true
End procedure
Dequeue Operation

Data Structures
41

Accessing data from the queue is a process of two tasks − access the data
where front is pointing and remove the data after access. The following steps
are taken to perform dequeue operation:
Step 1 − Check if the queue is empty.
Step 2 − If the queue is empty, produce underflow error and exit.
Step 3 − If the queue is not empty, access the data where front is pointing.
Step 4 − Increment front pointer to point to the next available data element.
Step 5 − Return success.
Procedure dequeue
if queue is empty
return underflow
end if
data = queue[front]
front = front + 1
return true
end procedure
peek( )
This function helps to see the data at the front of the queue. The algorithm of
peek() function is as follows
begin procedure peek
return queue[front]
end procedure
isFull:
As we are using single dimension array to implement queue, we just check for
the rear pointer to reach at MAXSIZE to determine that the queue is full.
Begin procedure isfull
if rear equals to MAXSIZE
return true
else
return false
end if
end procedure
Applications of Queue:
Printing using the computer: When several documents are to be printed, the
printer prints the documents in FIFO method only. i.e. to keep track of
documents in FIFO order, a queue is used.
Reservation system: Reservations such as air ticket or railway reservation
systems, use to issue reservations on first come first serve basis i.e. FIFO
method.

Data Structures
42

Computer networks: Computer networks use queue to give access from server
to several clients, who are connected to the server in FIFO method.

BFS: Breadth first search uses a queue data structure to find an element from
a graph.

What is a queue? Explain types of queue.

 Queue is a Linear Data Structure that works on First-in-First-Out (FIFO)


principle.
 It has two pointers, ―Front‖ that point to the beginning of the queue and
―Rear‖ that points to the end of the queue.
 The ―Front‖ and ―Rear‖ pointers are manipulated constantly to always
point to the beginning and end of queue.

Different types of queues:


1. Simple queue
2. Circular queue
3. Priority queue
4. Dequeue (Double ended queue)
1.Simple or linear queue
 Simple or standard Queue is a linear data structure in which the
insertion and deletion operations are performed at two different ends.
 In a simple queue data structure, the insertion operation is performed at
a position which is known as 'rear' and the deletion operation is
performed at a position which is known as 'front'.

2. Circular queue:
 Circular queue is a linear data structure. It follows FIFO principle. In
circular queue the last node is connected back to the first node to make
a circle.
 Elements are added at the rear end and the elements are deleted at front
end of the queue
 It is also called as ―Ring buffer‖.

Data Structures
43

Applications of circular queue:

Adding large integers: large integers can be added very easily using circular
queues. Here the right most digit is placed in the front node and left most digit
is placed in rear node.

Memory management: The unused memory locations in the case of ordinary


queues can be utilised in circular queues.

Computer controlled traffic system: In computer controlled traffic system,


circular queues are used to switch on the traffic lights one by one repeatedly as
per the time set.

3. Priority queue:
A priority queue is a queue that contains items that have some preset
priority.When an element has to be removed from a priority queue, the item with
the highest pririty is removed first.

 An element of higher priority is processed before any element of lower


priority.
 Two elements with same priority are processed according to the order in
which they were added to the queue.

4. Double ended Queue


Double Ended Queue is also a Queue data structure in which the insertion and
deletion operations are performed at both the ends (front and rear). That
means, we can insert at both front and rear positions and can delete from both
front and rear positions.

Double Ended Queue can be represented in TWO ways, those are as follows...

 Input Restricted Double Ended Queue


 Output Restricted Double Ended Queue

Input Restricted Double Ended Queue


In input restricted double ended queue, the insertion operation is performed at
only one end and deletion operation is performed at both the ends.

Data Structures
44

Output Restricted Double Ended Queue


In output restricted double ended queue, the deletion operation is performed at
only one end and insertion operation is performed at both the ends.

What is a circular queue ? explain its operations ?

 In a standard queue data structure re-buffering problem occurs for each


dequeue operation. To solve this problem by joining the front and rear ends
of a queue to make the queue as a circular queue
 Circular queue is a linear data structure. It follows FIFO principle. In
circular queue the last node is connected back to the first node to make a
circle.
 Elements are added at the rear end and the elements are deleted at front
end of the queue
 It is also called as ―Ring buffer‖.

Limitations:
The drawback of circular queue is , difficult to distinguished the full and empty cases.
It is also known as boundary case problem.

Circular Queue can be created in three ways they are


 Using single linked list
 Using double linked list
 Using arrays

Data Structures
45

Algorithm for Enqueue operation using array


Step 1: start
Step2: if (front == (rear+1)%max) Print error ―circular queue overflow ―
Step3: else
{ rear = (rear+1)%max
Q[rear] = element;
If (front == -1 ) f = 0;
}
Step 4 :stop
Algorithm for Dequeue operation using array
Step 1: start
Step2: if ((front == rear) && (rear == -1)) print error “circular queue underflow “
Step3: else
{ element = Q[front]
if (front == rear)
front=rear = -1
else
front = (front + 1) % max }
Step 4: stop

What is queue ? Explain Array and linked representation of Queues.

 Queue is a Linear Data Structure that works on First-in-First-Out (FIFO)


principle.
 It has two pointers, ―Front‖ that point to the beginning of the queue and
―Rear‖ that points to the end of the queue.
 The ―Front‖ and ―Rear‖ pointers are manipulated constantly to always
point to the beginning and end of queue.

There are two ways to represent a queue in memory.


1. Using an array
2. Using a linked list

Data Structures
46

The first kind of representation uses a one dimensional array and it is a better
a choice where a queue of fixed size is required. The other representation uses
double linked list and provides queue whose size can vary during processing.
Represntation of Queue using an array:
A one dimensional array, say q[1…N], can beused to represent a queue.

In the above representation, two pointers namely FRONT and REAR are used to indicate
the two ends of the queue. For the insertion of the next element, the pointer REAR will be
the consultant and for the pointer FRONT will be the consultant. Three states of a queue
with this representation are given below.

Queue is empty:
FRONT =0,
REAR=0
Queue is full
REAR=N
FRONT=1
Queue contains elements >=1
Number of elelnts = REAR-FRONT+1
Representation of a Queue using linked list:
A Linear Queue can be represented as a Linked List. For this we need two
variables front and rear to keep track of the two ends of the Queue. There are
two possibilities for binding these two variables to the ends of the Linked list.
The nodes can be linked from front to rear or rear to front. But linking the
nodes from front to rear is more efficient for deletions.
Queue is empty
FRONT =REAR=HEADER
HEADERRLINK=NULL
QUEUE contains at least one element
HEADER RLINK ≠ NULL

Data Structures

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy