0% found this document useful (0 votes)
21 views24 pages

Ds Mod 1

Uploaded by

xcr6p6ysq7
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)
21 views24 pages

Ds Mod 1

Uploaded by

xcr6p6ysq7
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/ 24

MODULE 1

IMPLEMENT THE PRIMITIVE OPERATIONS AND APPLICATIONS OF


STACK AND QUEUES

Data Structure is a branch of Computer Science. The study of data structure


allows us to understand the organization of data and the management of the data
flow in order to increase the efficiency of any process or program. Data Structure
is a particular way of storing and organizing data in the memory of the computer
so that these data can easily be retrieved and efficiently utilized in the future when
required.

BASIC TERMINOLOGIES OF DATASTRUCTURE

Data Structures are the building blocks of any software or program. Selecting the
suitable data structure for a program is an extremely challenging task for a
programmer.

The following are some fundamental terminologies used whenever the data
structures are involved:

● Data: We can define data as an elementary value or a collection of values.


For example, the Employee's name and ID are the data related to the
Employee.

● Data Items: A Single unit of value is known as Data Item.

● Group Items: Data Items that have subordinate data items are known as
Group Items. For example, an employee's name can have a first, middle,
and last name.

● Elementary Items: Data Items that are unable to divide into sub-items are
known as Elementary Items. For example, the ID of an Employee.

1
● Entity and Attribute: A class of certain objects is represented by an Entity.
It consists of different Attributes. Each Attribute symbolizes the specific
property of that Entity. For example,

Attributes ID Name Gender Job Title


Values 1234 Stacey M. Hill Female Software Developer

Entities with similar attributes form an Entity Set. Each attribute of an entity set
has a range of values, the set of all possible values that could be assigned to the
specific attribute.

The term "information" is sometimes utilized for data with given attributes of
meaningful or processed data.

● Field: A single elementary unit of information symbolizing the Attribute of


an Entity is known as Field.

● Record: A collection of different data items are known as a Record. For


example, if we talk about the employee entity, then its name, id, address,
and job title can be grouped to form the record for the employee.

● File: A collection of different Records of one entity type is known as a File.


For example, if there are 100 employees, there will be 25 records in the
related file containing data about each employee.

CLASSIFICATION OF DATASTRUCTURE

A Data Structure delivers a structured set of variables related to each other in


various ways. It forms the basis of a programming tool that signifies the
relationship between the data elements and allows programmers to process the
data efficiently.

2
We can classify Data Structures into two categories:

● Primitive Data Structure

● Non-Primitive Data Structure

Primitive Data Structures


● Primitive Data Structures are the data structures consisting of the
numbers and the characters that come in-built into programs.

● These data structures can be manipulated or operated directly by


machine-level instructions.

● Basic data types like Integer, Float, Character, and Boolean come under
the Primitive Data Structures.

● These data types are also called Simple data types, as they contain
characters that can't be divided further

Non-Primitive Data Structures


● Non-Primitive Data Structures are those data structures derived from
Primitive Data Structures.

3
● These data structures can't be manipulated or operated directly by
machine-level instructions.

● The focus of these data structures is on forming a set of data elements that
is either homogeneous (same data type) or heterogeneous (different data
types).

● Based on the structure and arrangement of data, we can divide these data
structures into two sub-categories -

a. Linear Data Structures

b. Non-Linear Data Structures

Linear Data Structures


A data structure that preserves a linear connection among its data elements is
known as a Linear Data Structure. The arrangement of the data is done linearly,
where each element consists of the successors and predecessors except the first
and the last data element. However, it is not necessarily true in the case of
memory, as the arrangement may not be sequential.

Based on memory allocation, the Linear Data Structures are further classified into
two types:

● Static Data Structures: The data structures having a fixed size are known
as Static Data Structures. The memory for these data structures is allocated
at the compiler time, and their size cannot be changed by the user after
being compiled; however, the data stored in them can be altered.
The Array is the best example of the Static Data Structure as they have a
fixed size, and its data can be modified later.

● Dynamic Data Structures: The data structures having a dynamic size are
known as Dynamic Data Structures. The memory of these data structures is
allocated at the run time, and their size varies during the run time of the
code. Moreover, the user can change the size as well as the data elements

4
stored in these data structures at the run time of the code.
Linked Lists, Stacks, and Queues are common examples of dynamic data
structures

Characteristics of Linear Data Structure:


*Sequential Organization: In linear data structures, data elements
are arranged sequentially, one after the other. Each element has a
unique predecessor (except for the first element) and a unique
successor (except for the last element)
*Order Preservation: The order in which elements are added to
the data structure is preserved. This means that the first element
added will be the first one to be accessed or removed, and the
last element added will be the last one to be accessed or
removed.
*Fixed or Dynamic Size: Linear data structures can have either
fixed or dynamic sizes. Arrays typically have a fixed size when they
are created, while other structures like linked lists, stacks, and
queues can dynamically grow or shrink as elements are added or
removed.
*Efficient Access: Accessing elements within a linear data
structure is typically efficient. For example, arrays offer
constant-time access to elements using their index.

Linear data structures are commonly used for organising


and manipulating data in a sequential fashion. Some of the most
common linear data structures include:

Arrays: A collection of elements stored in contiguous memory


locations.
Linked Lists: A collection of nodes, each containing an element
and a reference to the next node.
Stacks: A collection of elements with Last-In-First-Out (LIFO) order.
Queues: A collection of elements with First-In-First-Out (FIFO)
order.

2. Non-linear Data Structure:

5
A data structure is said to be non-linear if the data are not arranged in sequence or
a linear. The insertion and deletion of data is not possible in linear fashion. Trees
and graphs are the examples of non-linear data structure.

● Trees

A Tree is a Non-Linear Data Structure and a hierarchy containing a collection of


nodes such that each node of the tree stores a value and a list of references to other
nodes

● Graphs

A Graph is another example of a Non-Linear Data Structure comprising a finite


number of nodes or vertices and the edges connecting them

DATA STRUCTURES OPERATIONS

The data appearing in data structures are processed by means of certain operations.
The following four operations play a major role in this text:

1. Traversing: accessing each record/node exactly once so that certain items in the record may be
processed. (This accessing and processing is sometimes called “visiting” the record.)

2. Searching: Finding the location of the desired node with a given key value, or finding the
locations of all such nodes which satisfy one or more conditions.

3. Inserting: Adding a new node/record to the structure.

4. Deleting: Removing a node/record from the structure.

The following two operations, which are used in special situations:

1. Sorting: Arranging the records in some logical order

2. Merging: Combining the records in two different sorted files into a single sorted file.

6
STACKS AND QUEUES
STACKS
A Stack is linear data structure. A stack is a list of elements in which an element may be
inserted or deleted only at one end, called the top of the stack. Stack principle is LIFO (last
in, first out). Which element inserted last on to the stack that element deleted first from the
stack.

As the items can be added or removed only from the top i.e. the last item to be added to a
stack is the first item to be removed.

Real life examples of stacks are:

Operations on stack:

The two basic operations associated with stacks are:


1. Push
2. Pop

While performing push and pop operations the following test must be conducted on the
stack.
a) Stack is empty or not b) stack is full or not

1. Push: Push operation is used to add new elements in to the stack. At the time of addition
first check the stack is full or not. If the stack is full it generates an error message "stack
overflow".

2. Pop: Pop operation is used to delete elements from the stack. At the time of deletion first
check the stack is empty or not. If the stack is empty it generates an error message "stack
underflow".

All insertions and deletions take place at the same end, so the last element added to
the stack will be the first element removed from the stack. When a stack is created, the
stack base remains fixed while the stack top changes as elements are added and removed.
The most accessible element is the top and the least accessible element is the bottom of the
stack.

Array Representation of Stack (or) Implementation of stack:


Let us consider a stack with 6 elements capacity. This is called as the size of the stack.
The number of elements to be added should not exceed the maximum size of the stack. If
we attempt to add new element beyond the maximum size, we will encounter a stack
overflow condition. Similarly, you cannot remove elements beyond the base of the stack. If
such is the case, we will reach a stack underflow condition.

1.push():When an element is added to a stack, the operation is performed by push(). Below


Figure shows the creation of a stack and addition of elements using push().

Initially top=-1, we can insert an element in to the stack, increment the top value i.e top=top+1.
We can insert an element in to the stack first check the condition is stack is full or not. i.e
top>=size-1. Otherwise add the element in to the stack.
void push() Algorithm: Procedure for push():
{
int x; Step 1: START
if(top >= n-1) Step 2: if top>=size-1 then
{ Write “ Stack is Overflow”
printf("\n\nStack Step 3: Otherwise
Overflow.."); 3.1: read data value ‘x’
return; 3.2: top=top+1;
} 3.3: stack[top]=x;
else Step 4: END
{
printf("\n\nEnter data: ");
scanf("%d", &x);
stack[top] = x;
top = top + 1;
printf("\n\nData Pushed into
the stack");
}
}

8
2.Pop(): When an element is taken off from the stack, the operation is performed by pop().
Below figure shows a stack initially with three elements and shows the deletion of elements
using pop().
We can insert an element from the stack, decrement the top value i.e top=top-1. We can
delete an element from the stack first check the condition is stack is empty or not. i.e
top==-1. Otherwise remove the element from the stack.
Void pop() Algorithm: procedure pop():
{ Step 1: START
If(top==-1) Step 2: if top==-1 then
{ Write “Stack is Underflow”
Printf(“Stack is Underflow”); Step 3: otherwise
} 3.1: print “deleted element”
else 3.2: top=top-1;
{ Step 4: END
printf(“Delete data %d”,stack[top]);
top=top-1;
}
}

3.display(): This operation performed display the elements in the stack. We display the
element in the stack check the condition is stack is empty or not i.e top==-1.Otherwise
display the list of elements in the stack.
9
void display() Algorithm: procedure pop():
{ Step 1: START
If(top==-1) Step 2: if top==-1 then
{ Write “Stack is Underflow”
Printf(“Stack is Underflow”); Step 3: otherwise
} 3.1: print “Display elements are”
else 3.2: for top to 0
{ Print ‘stack[i]’
printf(“Display elements are:); Step 4: END
for(i=top;i>=0;i--)
printf(“%d”,stack[i]);
}
}

Applications of stack:
1. Stack is used by compilers to check for balancing of parentheses, brackets and braces.
2. Stack is used to evaluate a postfix expression.
3. Stack is used to convert an infix expression into postfix/prefix form.
4. In recursion, all intermediate arguments and return values are stored on the processor’s
stack.
5. During a function call the return address and arguments are pushed onto a stack and on
return they are popped off.

Converting and evaluating Algebraic expressions:


An algebraic expression is a legal combination of operators and operands. Operand is the
quantity on which a mathematical operation is performed. 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
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

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 +
Conversion from infix to postfix:
Procedure to convert from infix expression to postfix expression is as follows:
1. Scan the infix expression from left to right.
2. a) If the scanned symbol is left parenthesis, push it onto the stack.
b) If the scanned symbol is an operand, then place directly in the postfix expression
(output).
c) If the symbol scanned is a right parenthesis, then go on popping all the items from the
stack and place them in the postfix expression till we get the matching left parenthesis. d)
If the scanned symbol is an operator, then go on removing all the operators from the stack
and place them in the postfix expression, if and only if the precedence of the operator
which is on the top of the stack is greater than (or greater than or equal) to the
precedence of the scanned operator and push the scanned operator onto the stack
otherwise, push the scanned operator onto the stack.
The three important features of postfix expression are:
1. The operands maintain the same order as in the equivalent infix expression. 2. The
parentheses are not needed to designate the expression unambiguously. 3. While
evaluating the postfix expression the priority of the operators is no longer relevant.

We consider five binary operations: +, -, *, / and $ or ↑ (exponentiation). For these binary


operations, the following in the order of precedence (highest to lowest):

13
Evaluation of postfix expression:
The postfix expression is evaluated easily by the use of a stack.
1. When a number is seen, it is pushed onto the stack;
2. When an operator is seen, the operator is applied to the two numbers that are
popped from the stack and the result is pushed onto the stack.
3. When an expression is given in postfix notation, there is no need to know any
precedence rules; this is our obvious advantage.
QUEUE
A queue is linear data structure and collection of elements. A queue is another special kind
of list, where items are inserted at one end called the rear and deleted at the other end
called the front. The principle of queue is a “FIFO” or “First-in-first-out”. Queue is an
abstract data structure. A queue is a useful data structure in programming. It is similar to
the ticket queue outside a cinema hall, where the first person entering the queue is the first
person who gets the ticket.
A real-world example of queue can be a single-lane one-way road, where the vehicle enters
first, exits first.
More
real-world examples can be seen as queues at the ticket windows and bus-stops and our
college library.

The
operations for a queue are analogues to those for a stack; the difference is that the
insertions go at the end of the list, rather than the beginning.
Operations on QUEUE:
A queue is an object or more specifically an abstract data structure (ADT) that allows the
following operations:
∙ Enqueue or insertion: which inserts an element at the end of the queue. ∙
Dequeue or deletion: which deletes an element at the start of the queue. Queue
operations work as follows:
1. Two pointers called FRONT and REAR are used to keep track of the first and last
elements in the queue.
2. When initializing the queue, we set the value of FRONT and REAR to 0. 3. On enqueing
an element, we increase the value of REAR index and place the new element in the
position pointed to by REAR.
4. On dequeueing an element, we return the value pointed to by FRONT and increase the
FRONT index.
5. Before enqueing, we check if queue is already full.
6. Before dequeuing, we check if queue is already empty.
7. When enqueing the first element, we set the value of FRONT to 1.
8. When dequeing the last element, we reset the values of FRONT and REAR to 0.
Representation of Queue (or) Implementation of Queue:
The queue can be represented in two ways:
1. Queue using Array
2. Queue using Linked List
1.Queue using Array:
Let us consider a queue, which can hold maximum of five elements. Initially the queue is
empty.

Now, insert 11 to the queue. Then queue status will be:


Next, insert 22 to the queue. Then the queue status is:

Again insert another element 33 to the queue. The status of the queue is:

Now, delete an element. The element deleted is the element at the front of the queue.So
the status of the queue is:

Again, delete an element. The element to be deleted is always pointed to by the FRONT
pointer. So, 22 is deleted. The queue status is as follows:

Now, insert new elements 44 and 55 into the queue. The queue status is:

Next insert another element, say 66 to the queue. We cannot insert 66 to the queue as the
rear crossed the maximum size of the queue (i.e., 5). There will be queue full signal. The
queue status is as follows:

Now it is not possible to insert an element 66 even though there are two vacant positions in
the linear queue. To overcome this problem the elements of the queue are to be shifted
towards the beginning of the queue so that it creates vacant position at the rear end. Then
the FRONT and REAR are to be adjusted properly. The element 66 can be inserted at the rear
end. After this operation, the queue status is as follows:
This difficulty can overcome if we treat queue position with index 0 as a position that comes
after position with index 4 i.e., we treat the queue as a circular queue.

Queue operations using array:


a.enqueue() or insertion():which inserts an element at the end of the queue.
void insertion() Algorithm: Procedure for
{ insertion(): Step-1:START
if(rear==max) Step-2: if rear==max then
printf("\n Queue is Full"); Write ‘Queue is full’
else Step-3: otherwise
{ 3.1: read element ‘queue[rear]’
printf("\n Enter no %d:",j++); Step-4:STOP
scanf("%d",&queue[rear++]); }
}

b.dequeue() or deletion(): which deletes an element at the start of the queue.


void deletion() Algorithm: procedure for
{ deletion(): Step-1:START
if(front==rear) Step-2: if front==rear then
{ Write’ Queue is empty’
printf("\n Queue is empty"); Step-3: otherwise
} 3.1: print deleted element
else Step-4:STOP
{
printf("\n Deleted Element is
%d",queue[front++]);
x++;
}}

c.dispaly(): which displays an elements in the queue.


void deletion() Algorithm: procedure for
{ deletion(): Step-1:START
if(front==rear) Step-2: if front==rear then
{ Write’ Queue is empty’
printf("\n Queue is empty"); Step-3: otherwise
} 3.1: for i=front to rear then
else 3.2: print ‘queue[i]’
{ Step-4:STOP
for(i=front; i<rear; i++)
{
printf("%d",queue[i]);
printf("\n");
}
}
}
Applications of Queue:
1. It is used to schedule the jobs to be processed by the CPU.
2. When multiple users send print jobs to a printer, each printing job is kept in the printing
queue. Then the printer prints those jobs according to first in first out (FIFO) basis. 3. Breadth
first search uses a queue data structure to find an element from a graph.
TYPES OF QUEUES
There are four different types of queue that are listed as follows –
o Simple Queue or Linear Queue

o Circular Queue

o Priority Queue

o Double Ended Queue (or Deque)

1. SIMPLE OR LINEAR QUEUE

● In Linear Queue, an insertion takes place from one end while the deletion
occurs from another end.
● The end at which the insertion takes place is known as the rear end, and the
end at which the deletion takes place is known as front end.
● It strictly follows the FIFO rule.

● The major drawback of using a linear Queue is that insertion is done only
from the rear end.
● If the first three elements are deleted from the Queue, we cannot insert
more elements even though the space is available in a Linear Queue.
● In this case, the linear Queue shows the overflow condition as the rear is
pointing to the last element of the Queue

1
2. CIRCULAR QUEUE

● In Circular Queue, all the nodes are represented as circular.


● It is similar to the linear Queue except that the last element of the queue is
connected to the first element.
● It is also known as Ring Buffer, as all the ends are connected to another
end. The representation of circular queue is shown in the below image -

● The drawback that occurs in a linear queue is overcome by using the


circular queue.
● If the empty space is available in a circular queue, the new element can be
added in an empty space by simply incrementing the value of rear.
● The main advantage of using the circular queue is better memory
utilization.

3. PRIORITY QUEUE

● It is a special type of queue in which the elements are arranged based on the
priority.
● It is a special type of queue data structure in which every element has a
priority associated with it.
● Suppose some elements occur with the same priority, they will be arranged
according to the FIFO principle.
● The representation of priority queue is shown in the below image -

2
● Insertion in priority queue takes place based on the arrival, while deletion in
the priority queue occurs based on the priority.
● Priority queue is mainly used to implement the CPU scheduling algorithms.

There are two types of priority queue that are discussed as follows -

o Ascending priority queue –

● In ascending priority queue, elements can be inserted in arbitrary order,


but only smallest can be deleted first. Suppose an array with elements
7, 5, and 3 in the same order, so, insertion can be done with the same
sequence, but the order of deleting the elements is 3, 5, 7.

o Descending priority queue –

● In descending priority queue, elements can be inserted in arbitrary


order, but only the largest element can be deleted first. Suppose an
array with elements 7, 3, and 5 in the same order, so, insertion can be
done with the same sequence, but the order of deleting the elements is
7, 5, 3.

3
4. DEQUE (or, Double Ended Queue)

● In Deque or Double Ended Queue, insertion and deletion can be done


from both ends of the queue either from the front or rear.

● It means that we can insert and delete elements from both front and
rear ends of the queue.

● Deque can be used as a palindrome checker means that if we read the


string from both ends, then the string would be the same.
● Deque can be used both as stack and queue as it allows the insertion
and deletion operations on both ends.
● Deque can be considered as stack because stack follows the LIFO
(Last In First Out) principle in which insertion and deletion both can be
performed only from one end.
● And in deque, it is possible to perform both insertion and deletion from
one end, and Deque does not follow the FIFO principle.

The representation of the deque is shown in the below image -

4
There are two types of deque that are discussed as follows -

o Input restricted deque –

As the name implies, in input restricted queue, insertion operation can be


performed at only one end, while deletion can be performed from both
ends.

Output restricted deque –


As the name implies, in output restricted queue, deletion operation can be
performed at only one end, while insertion can be performed from both
ends.

5
1. Difference between stacks and Queues?
stacks Queues

1.A stack is a linear list of elements in 1.A Queue is a linerar list of elements in
which the element may be inserted or which the elements are added at one end
deleted at one end. and deletes the elements at another end. 2.
. In Queue the element which is inserted
2. In stacks, elements which are first is the element deleted first.
inserted last is the first element to be
deleted. 3. Queues are called FIFO (First In
First Out)list.
3.Stacks are called LIFO (Last In
First Out)list 4. In Queue elements are removed in
the same order in which thy are
4.In stack elements are removed in inserted.
reverse order in which thy are inserted.
5. Suppose the elements a,b,c,d,e are
5.suppose the elements a,b,c,d,e inserted in the Queue, the deletion of
are inserted in the stack, the elements will be in the same order in which
deletion of elements will be thy are inserted.
e,d,c,b,a.
6. In Queue there are two pointers one
6.In stack there is only one pointer to for insertion called “Rear” and another
insert and delete called “Top”. for deletion called “Front”.

7.Initially top=-1 indicates a stack is empty. 7. Initially Rear=Front=-1 indicates a Queue


is empty.
8.Stack is full represented by the
condition TOP=MAX-1(if array index 8.Queue is full represented by the
starts from ‘0’). condition Rear=Max-1.

9.To push an element into a stack, Top 9.To insert an element into Queue, Rear
is incremented by one is incremented by one.

10.To POP an element from stack,top 10.To delete an element from Queue, Front is
is decremented by one.

26
11.The conceptual view of Stack is incremented by one.
as follows:
11.The conceptual view of Queue is
as follows:

You might also like