0% found this document useful (0 votes)
2 views78 pages

Unit 4

Uploaded by

nehal.arora
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)
2 views78 pages

Unit 4

Uploaded by

nehal.arora
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/ 78

Unit 4

Modeled Data Structures


Stacks and Queue
Stack ADT

⚫ What is a Stack?
⚫ Stack is a linear data structure in which the
insertion and deletion operations are
performed at only one end.
⚫ In a stack, adding and removing of elements
are performed at a single position which is
known as "top". That means, a new element is
added at top of the stack and an element is
removed from the top of the stack.
⚫ In stack, the insertion and deletion operations
are performed based on LIFO (Last In First
Out) principle.
Stack
⚫ A stack data structure can be defined as
follows...
⚫ Stack is a linear data structure in which the
operations are performed based on LIFO
principle.
⚫ Stack can also be defined as
⚫ "A Collection of similar data items in which
both insertion and deletion operations are
performed based on LIFO principle".
LIFO Principle of Stack
⚫ In programming terms, putting an item on
top of the stack is called push and removing
an item is called pop.
Push and Pop Operations in Stack
⚫ In a stack, the insertion operation is
performed using a function called "push" and
deletion operation is performed using a
function called "pop".
⚫ In the figure, PUSH and POP operations are
performed at a top position in the stack. That
means, both the insertion and deletion
operations are performed at one end (i.e., at
Top)
Stack using array

.
Basic operations on stack
⚫ In order to make manipulations in stack, there are certain
operations
⚫ push() to insert an element into the stack
⚫ pop() to remove an element from the stack
⚫ top() Returns the top element of the stack.
⚫ isEmpty() returns true is stack is empty else false
⚫ peek(): Return the top element
Example

⚫ If we want to create a stack by inserting


10,45,12,16,35 and 50. Then 10 becomes the
bottom-most element and 50 is the topmost
element. The last inserted element 50 is at
Top of the stack as shown in the image
below...
Operations on a Stack
⚫ The following operations are performed on
the stack...
⚫ Push (To insert an element on to the stack)
⚫ Pop (To delete an element from the stack)
⚫ Display (To display elements of the stack)
⚫ Stack data structure can be implemented in
two ways::
⚫ Using Array
⚫ Using Linked List
⚫ When a stack is implemented using an array,
that stack can organize an only limited
number of elements.
⚫ When a stack is implemented using a linked
Push Operation:
⚫ Adding an element onto the stack (push operation)
⚫ Adding an element into the top of the stack is
referred to as push operation. Push operation
involves following two steps.
⚫ Increment the variable Top so that it can now
refere to the next memory location.
⚫ Add element at the position of incremented top.
This is referred to as adding new element at the
top of the stack.
⚫ Algorithm
⚫ begin
⚫ if top = n then stack full
⚫ top = top + 1
⚫ stack (top) : = item;
⚫ end

⚫ Time Complexity : o(1)


Pop Operation:

⚫ Deletion of an element from the top of the


stack is called pop operation.
⚫ The top most element of the stack is stored in
an another variable and then the top is
decremented by 1. the operation returns the
deleted value that was stored in another
variable as the result.
⚫ Algorithm :
⚫ begin
⚫ if top = 0 then stack empty;
⚫ item := stack(top);
⚫ top = top - 1;
⚫ end;
Array implementation using stack
Array implementation using stack

.
Stack Using Link List
Drawbacks of stack using array

⚫ The major problem with the stack implemented


using an array is, it works only for a fixed number
of data values.
⚫ That means the amount of data must be specified
at the beginning of the implementation itself.
⚫ Stack implemented using an array is not suitable,
when we don't know the size of data which we are
going to use.
⚫ The stack implemented using linked list can work
for an unlimited number of values.
⚫ So, there is no need to fix the size at the
beginning of the implementation.
Linked list implementation
⚫ In linked list implementation of a stack, every
new element is inserted as 'top' element.
⚫ That means every newly inserted element is
pointed by 'top'.
⚫ Whenever we want to remove an element from
the stack, simply remove the node which is
pointed by 'top' by moving 'top' to its previous
node in the list.
⚫ The next field of the first element must be
always NULL.
⚫ In the above example, the last inserted node is 99
and
the first inserted node is 25.
The order of elements inserted is
25, 32,50 and 99.
Link list implementation

.
Stack operation using link list

⚫ void push(in x)
⚫ {
⚫ ListNode *newNode;
⚫ newNode=new ListNode;
⚫ newNode->info=x;
⚫ newNode->link=head;
⚫ head=newNode;
⚫ }
Stack operation using Link list

⚫ Pop()
⚫ int pop()
⚫ {
⚫ int x=head->info;
⚫ head=head->link;
⚫ return x;
⚫ }
Advantages of stack using Link list

.
Expression
⚫ An expression is a collection of operators and
operands that represents a specific value.
⚫ In above definition, operator is a symbol
which performs a particular task like
arithmetic operation or logical operation or
conditional operation etc.,
Operands are the values on which the
operators can perform the task.
⚫ Expression Types
⚫ Based on the operator position, expressions
are divided into THREE types. They are as
follows...
⚫ Infix Expression
⚫ Postfix Expression
⚫ Prefix Expression
Infix Expression

⚫ In infix expression, operator is used in


between the operands.
The general structure of an Infix expression
is as follows...
Postfix Expression

⚫ In postfix expression, operator is used after


operands. We can say that "Operator follows
the Operands".

The general structure of Postfix expression is


as follows...
Prefix Expression
⚫ In prefix expression, operator is used
before operands. We can say that
"Operands follows the Operator".

The general structure of Prefix expression


is as follows...
Definition of Infix, Postfix, and Prefix
⚫ Infix: The typical mathematical form of
expression that we encounter generally is known
as infix notation. In infix form, an operator is
written in between two operands.
⚫ For example:
⚫ An expression in the form of A * ( B + C ) / D is in
infix form. This expression can be simply decoded
as: “Add B and C, then multiply the result by A, and then
divide it by D for the final answer.”
⚫ Prefix: In prefix expression, an operator is written
before its operands. This notation is also known as
“Polish notation”.
⚫ For example, The above expression can be written
in the prefix form as / * A + B C D. This type of
expression cannot be simply decoded as infix
expressions.
⚫ Postfix: In postfix expression, an operator is
written after its operands. This notation is also
known as “Reverse Polish notation”.
Infix,Prefix and postfix expressions
⚫ Refer to the table below to understand these
expressions with some examples
⚫ Rules for the conversion from infix to postfix
expression
⚫ Print the operand as they arrive.
⚫ If the stack is empty or contains a left parenthesis
on top, push the incoming operator on to the stack.
⚫ If the incoming symbol is '(', push it on to the stack.
⚫ If the incoming symbol is ')', pop the stack and
print the operators until the left parenthesis is
found.
⚫ If the incoming symbol has higher precedence
than the top of the stack, push it on the stack.
⚫ If the incoming symbol has lower precedence than
the top of the stack, pop and print the top of the
stack. Then test the incoming operator against the
new top of the stack.
⚫ If the incoming operator has the same precedence
with the top of the stack then use the associativity
rules. If the associativity is from left to right then
pop and print the top of the stack then push the
incoming operator. If the associativity is from right
Convert infix to postfix expression
Algorithm
Infix to Postfix Conversion

⚫ Any expression can be represented using three


types of expressions (Infix, Postfix, and Prefix).
We can also convert one type of expression to
another type of expression like Infix to Postfix,
Infix to Prefix, and vice versa.

To convert any Infix expression into Postfix or


Prefix expression we can use the following
procedure...
⚫ Find all the operators in the given Infix
Expression.
⚫ Find the order of operators evaluated
according to their Operator precedence.
⚫ Convert each operator into required type of
Example
⚫ Consider the following Infix Expression to be
converted into Postfix Expression...
⚫ D=A+B*C
⚫ Step 1 - The Operators in the given Infix
Expression : = , + , *
⚫ Step 2 - The Order of Operators according to
their preference : * , + , =
⚫ Step 3 - Now, convert the first
operator * ----- D = A + B C *
⚫ Step 4 - Convert the next operator + ----- D
= A BC* +
⚫ Step 5 - Convert the next operator = ----- D
ABC*+ =
⚫ Finally, given Infix Expression is converted
into Postfix Expression as follows...
Infix to Postfix Conversion using Stack Data Structure

⚫ To convert Infix Expression into Postfix


Expression using a stack data structure, We can
use the following steps...
⚫ Read all the symbols one by one from left to right
in the given Infix Expression.
⚫ If the reading symbol is operand, then directly
print it to the result (Output).
⚫ If the reading symbol is left parenthesis '(', then
Push it on to the Stack.
⚫ If the reading symbol is right parenthesis ')', then
Pop all the contents of stack until respective left
parenthesis is poped and print each poped
symbol to the result.
⚫ If the reading symbol is operator (+ , - , * , / etc.,),
then Push it on to the Stack. However, first pop
the operators which are already on the stack that
Algorithm for postfix conversion

.
Example:Convert infix expression into postfix

(A+B)*(C-D)
Example:Convert infix expression into postfix
(A+B/C+(D+E)-F
.
Example

.
Example:Convert infix expression into postfix

A+(B*C-(D/E-F)*G)*H
Evaluation of Postfix Expression

The Postfix notation is used to represent algebraic


expressions.
The steps mentioned below to evaluate postfix
expression using stack:-
⚫ Create a stack to store operands (or values).
⚫ Scan the given expression from left to right and
do the following for every scanned element.
⚫ If the element is a number, push it into the
stack
⚫ If the element is an operator, pop operands for
the operator from the stack. Evaluate the
operator and push the result back to the stack
⚫ When the expression is ended, the number in
the stack is the final answer
Algorithm :postfix Evaluation(postfix)

.
Evaluation of Postfix expressions

Evaluate P:5,6,2,+,*,12,4,/,-
Queue data structure

Queue in data structure can be accessed from


both of its sides (at the front for deletion and
back for insertion).
Queue representation as a data structure-
QUEUE
⚫ A queue is a linear data structure that follows
the First In, First Out (FIFO) principle, which
means that the element which is inserted first
in the queue will be the first one to be
removed from the queue.
What is a Queue?
⚫ Queue is a linear data structure in which the
insertion and deletion operations are
performed at two different ends.
⚫ In a queue data structure, adding and
removing elements are performed at two
different positions.
⚫ The insertion is performed at one end and
deletion is performed at another end.
⚫ In a 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'.
⚫ In queue data structure, the insertion and
Queue
• Initially both front and rear are set to -1
• When we insert a new value into the queue
,increment rear value by one and then insert
at that position.
• Whenever we want to delete a value from
the queue then delete the element which is
at front position and increment front value
by one
Queue
⚫ In a queue data structure, the insertion
operation is performed using a function
called "enQueue()" and deletion operation is
performed using a function called
"deQueue()".

Queue data structure can be defined as


follows...
⚫ Queue data structure is a linear data
structure in which the operations are
performed based on FIFO principle.
⚫ A queue data structure can also be defined as
⚫ "Queue data structure is a collection of
Example
⚫ Queue after inserting 25, 30, 51, 60 and 85
Operations on a Queue
⚫ The following operations are performed on a queue
data structure...
⚫ enQueue(value) –Add an element to the end of the
queue (To insert an element into the queue)
⚫ deQueue() –Remove an element from the front of
the queue (To delete an element from the queue)
Operations on a Queue

⚫ Enqueue and dequeue


Operations on a Queue

⚫ display() - (To display the elements of


the queue)
⚫ IsEmpty:check if queue is empty
⚫ IsFull:to check if queue is full
⚫ Peek:Get the value of the front of the
queue without removing it.
Queue data structure

⚫ Queue data structure can be implemented in


two ways. They are as follows...
⚫ Using Array
⚫ Using Linked List
⚫ When a queue is implemented using an array,
that queue can organize an only limited number
of elements.
⚫ When a queue is implemented using a linked
list, that queue can organize an unlimited
number of elements.
Queue using array

.
Queue using array

.
Deletion in queue

.
Examples:

.
Queue
⚫ A queue is a linear data structure that
follows the First in, First out
principle(FIFO). Queue supports
operations like enqueue and dequeue.
Queue using Link List
Queue using an array - drawback
⚫ If we implement the queue using an array, we
need to specify the array size at the beginning(at
compile time).
⚫ We can't change the size of an array at runtime. So,
the queue will only work for a fixed number of
elements.
⚫ Solution
⚫ We can implement the queue data structure using
the linked list.
⚫ In the linked list, we can change its size at runtime.
Node structure for Queue

⚫ struct node { int data; struct node *next; };


⚫ To point the front and rear node
⚫ struct node *front = NULL, *rear = NULL;
Enqueue Function

.
Enqueue function

.
Enqueue function

.
Dequeue function

Dequeue function will remove the first element


from the queue.
Insertion operation

⚫ Algorithm
⚫ Step 1: Allocate the space for the new node
PTR
⚫ Step 2: SET PTR -> DATA = VAL
⚫ Step 3: IF FRONT = NULL
SET FRONT = REAR = PTR
SET FRONT -> NEXT = REAR -> NEXT =
NULL
ELSE
SET REAR -> NEXT = PTR
SET REAR = PTR
SET REAR -> NEXT = NULL
[END OF IF]
⚫ Step 4: END
Deletion
⚫ Deletion operation removes the element
that is first inserted among all the queue
elements. Firstly, we need to check either
the list is empty or not
Deletion
⚫ Algorithm
⚫ Step 1: IF FRONT = NULL
Write " Underflow "
Go to Step 5
[END OF IF]
⚫ Step 2: SET PTR = FRONT
⚫ Step 3: SET FRONT = FRONT -> NEXT
⚫ Step 4: FREE PTR
⚫ Step 5: END
Operation on Linked Queue
⚫ Each node of a linked queue consists of two
fields: data and next(storing address of next
node). The data field of each node contains the
assigned value, and the next points to the node
containing the next item in the queue.
⚫ A linked queue consists of two pointers, i.e., the
front pointer and the rear pointer. The front
pointer stores the address of the first element of
the queue, and the rear pointer stores the address
of the last element of the queue.
⚫ Insertion is performed at the rear end, whereas
deletion is performed at the front end of the
queue. If front and rear both points to NULL, it
signifies that the queue is empty.
⚫ The two main operations performed on the
linked queue are:
⚫ Insertion
Insert operation

⚫ Insert operation or insertion on a linked


queue adds an element to the end of the
queue. The new element which is added
becomes the last element of the queue.
Insertion
⚫ Algorithm to perform Insertion on a linked queue:

⚫ 1.Create a new node pointer.


ptr = (struct node *) malloc (sizeof(struct node));
⚫ 2.Now, two conditions arise, i.e., either the queue is
empty, or the queue contains at least one element.
⚫ 3.If the queue is empty, then the new node added
will be both front and rear, and the next pointer of
front and rear will point to NULL.
Insertion

⚫ 4.If the queue contains at least one element, then


the condition front == NULL becomes false.
So, make next pointer of rear point to new node
ptr and point the rear pointer to the newly created
node ptr
Deletion
⚫ Deletion or delete operation on a linked queue
removes the element which was first inserted in
the queue, i.e., always the first element of the
queue is removed.
⚫ Steps to perform Deletion on a linked queue:
⚫ 1.Check if the queue is empty or not.
⚫ 2.If the queue is empty, i.e., front==NULL, so we
just print 'underflow' on the screen and exit.
⚫ 3.If the queue is not empty, delete the element at
which the front pointer is pointing. For deleting a
node, copy the node which is pointed by the front
pointer into the pointer ptr and make the front
pointer point to the front's next node and free the
node pointed by the node ptr. This can be done
using the following statement:
Steps for implementing queue using linked list:

1. Enqueue Function
⚫ Enqueue function adds an element to the end of the
queue. It takes O(1) time. The last element can be
tracked using the rear pointer.
⚫ First, build a new node with given data.
⚫ Check if the queue is empty or not.
⚫ If a queue is empty then, a new node is assigned to the
front and rear.
⚫ Else make next of rear as new node and rear as a new
node.

2. Dequeue Function
⚫ The dequeue function always removes the first
element of the queue. It takes O(1) time. For dequeue,
the queue must contain at least one element, else
underflow conditions will occur.
⚫ Check if queue is empty or not.
⚫ If the queue is empty, then dequeue is not possible.
⚫ Else store front in temp
Note:
⚫ Queue is a linear data structure that follows
the First in, First Out Principle (FIFO).
⚫ Queue can be represented using nodes of a
linked list.
⚫ Queue supports operations such as
enqueue, dequeue and print().
⚫ Elements can be enqueued from one end
and dequeued from the other one end.
⚫ Enqueue and Dequeue operations
take O(1) time.
Circular queue
A circular queue is a linear data structure in which
the operations are performed based on FIFO (First
In First Out) principle and the last position is
connected back to the first position to make a
circle. It is also called ring buffer
Circular queue

.
Circular queue
Enqueue operation

1.Check if the queue is full


2.For the first element ,set value of Front to 0
3.Circularly increase the Rear index y 1
4.Add the new element in the position pointed by
Rear
Dequeue operation

1.Check if the queue is empty


2.Return the value pointed by front
3.Circularly increase the front index by 1
4.For the last element ,reset the values
of front and rear to -1
Priority queue
⚫ In a priority queue, an element with high
priority is served before an element with low
priority
Priority Queue
⚫ Every item has a priority associated with it.
⚫ 1. An element with high priority is processed
before any element of low priority.
⚫ 2. If two elements have the same priority, they
are served according to their order in the
queue

You might also like