unit-1
unit-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.
1
2
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.
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
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
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
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
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.
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
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
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
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.
Physical Representation
Eg: Let M=4560 and w=1,calculate the address of A[0], A[2], A[7]
Data Structures
11
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.
Eg: Consider an array of size mxn, here m is the no.of rows and n is the no.of
columns as follows.
Data Structures
12
1. Row-Major Order
2. Column-Major Order
Eg:
a11 a12 a13
a21 a22 a23
a31 a32 a33
3X3
Memory Representation
Row-Major Order:
Address(aij) = (i-1)xn+j
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
= 4560+2x3+2-1
=4560+6+2-1 = 4567
Column-Major Order:
Address(aij) = (j-1)xm+j
If the base address is M, then the above formula can be modified as follows.
Address(aij) = M+(j-1)xm+i-1
= 4560+3+3-1
=4560+3+2 = 4565
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.`
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
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
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.
Data Structures
16
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
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_nodenext=START;
START =new_node;
Data Structures
19
while(pnext!=NULL)
{
p=pnext;
}
pnext=new_node;
new_nodenext=NULL;
while(p!=insert_position)
{
P=pnext;
}
store_next=pnext;
pnext=new_node;
new_nodenext=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.
Data Structures
21
B.Sc. IV SEMESTER
Data Structures
22
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.
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_nodenext=head;
headprev=new_node;
new_nodeprev=NULL;
head=new_node;
Data Structures
24
Data Structures
25
1. Deletion at beginnning
2. Deletion at middle
3. Deletion at end
Algorithm:
p=head;
head=headnext;
headprev=NULL;
delete(p);
Data Structures
26
P=pnext;
}
store_next=pnext;
store_prev=pprev;
store_nextprev=store_prev;
store_prevnext=store_next;
delete(p);
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
Algorithm:
store_prev=pprev;
store_prevnext=NULL;
delete(p);
Data Structures
27
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
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.
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.
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.
Data Structures
29
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
Main()
{
fun();
…………
…………
}
fun()
{
………..
Data Structures
31
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.
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.
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.
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_Headlink=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_Headlink;
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
Example: (A + B) * (C - D)
Example: * + A B – C D
Example: A B + C D - *
Data Structures
39
Data Structures
40
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
Queue operations :
Enqueue:
The process of adding an element into the queue is known as Enqueue. The
following steps are perform queue operations.
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.
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
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.
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.
Double Ended Queue can be represented in TWO ways, those are as follows...
Data Structures
44
Limitations:
The drawback of circular queue is , difficult to distinguished the full and empty cases.
It is also known as boundary case problem.
Data Structures
45
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
HEADERRLINK=NULL
QUEUE contains at least one element
HEADER RLINK ≠ NULL
Data Structures