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

DS Unit - 3 Ppts

Uploaded by

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

DS Unit - 3 Ppts

Uploaded by

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

STACKS

• Linear list.
• One end is called top.
• Other end is called bottom.
• Additions to and removals from the top end
only.

Dr.L.Lakshmi 1
STACK ADT
 A stack is a Last In First Out (LIFO) data structure in which all insertions and
deletions are takes place at one end, called the top.

 Stack maintains a variable called top, which keeps track of the top most element in
the stack.

 Any insertions or deletions should be based upon the value of top.

 In the stack, the elements are removed in the reverse order of that in which they were
added to the stack that is last element inserted is to be deleted first.

Basic Stack Operations:


push :To insert an item into stack
pop :To delete an item from stack
traversal :To display an items
isFull :To know whether the stack is full or not
isEmpty :To know whether the stack is empty or not

Dr.L.Lakshmi 2 2
STACK ADT
Example 1:
When the elements are inserted in the order as A,B,C,D then the size
of the stack is 4 and the top most element in the stack is D.
When deletion operation is performed on stack continuously then the order in which
the elements are deleted is D,C,B,A.

Dr.L.Lakshmi 3 3
STACKS


Standard operations:

IsEmpty … return true iff stack is empty

IsFull … return true iff stack has no remaining capacity

Top … return top element of stack

Push … add an element to the top of the stack

Pop … delete the top element of the stack

Dr.L.Lakshmi 4
STACKS
ADT Stack is
Object: a finite ordered list with 0 / more elements.
Functions:
for all stack belong Stack, item belong element, maxStackSize belongs
positive integer.
Stack Create(maxStackSize)::= create an empty stack whose maximum
size is maxStackSize
Boolean IsFull(stack ,maxStackSize)::=
if (number of elements in stack == maxStazkSize) return TRUE else
return FALSE
Stack Push(stack) ::=
if (IsFull(stack)) stackFull else insert item into top of stack and return
Boolean IsEmpty(stack) ::=
if (stack == CreateS(maxStackSize)) return TRUE else return FALSE
Element Pop(stack) ::=
if (IsEmpty(stack)) return else remove and return the element at the top of
the stack Dr.L.Lakshmi 5
STACK ADT
IMPLEMENTATION
Stack can be implemented in two ways:
1. using arrays
2. using linked list

Dr.L.Lakshmi 6 6
STACK ADT USING ARRAYS
STACK IMPLEMENTATION USING ARRAYS

Procedure:

 Initialize the stack by assigning -1 to the top variable to indicate that the array based
stack is empty.

 A top is an integer value, which contains the array index for the top of the stack.

 Each time data is pushed or popped, top is incremented or Decremented accordingly,


to keep track of the current top of the stack.

 Stacks implemented as arrays are useful if a fixed amount of data is to be used.

Dr.L.Lakshmi 7 7
STACK ADT USING ARRAYS
Algorithm for inserting an element into the stack

push()
1. if top>=size then
print “stack is full”
2. else
read item
top=top+1
stack[top]=item
endif
3. stop

The first step of this algorithm checks for an overflow condition.

Overflow occurs when we are trying to insert an item into a stack which is full.

If the top value reaches to maximum size of the stack then items cannot
be inserted into the stack i.e. stack is full.

Otherwise top is incremented by one and item is inserted into


Dr.L.Lakshmi 8 the stack. 8
STACK ADT USING ARRAYS
Push Functon
void push()
{
int ele;
if(top==SIZE-1)
{
printf("\n stack is full(overflow)\n");
return;
}
else
{
printf("enter the element to push:");
scanf("%d",&ele);
top++;
stack[top]=ele;
}

Dr.L.Lakshmi 9
STACK ADT USING ARRAYS
Algorithm for deleting an element from the stack

pop()

1. if top = -1 then
print “stack is empty”
2. else
1. item = stack[top]
2. top=top-1
3.endif
4.stop

The first step of this algorithm checks for underflow condition.

If the top value is -1 then stack is known as underflow or empty.

Takeout the element from the location where the top is pointing and
store it in the variable then decrement top by one.

Dr.L.Lakshmi 10 10
STACK ADT USING ARRAYS
POP Functon

void pop()
{
if(top==-1)
printf("\n stack is empty(underflow)\n");
else
printf("the pop element is:%d",stack[top]);
top--;
}

Dr.L.Lakshmi 11
STACK ADT USING ARRAYS
Algorithm for displaying an elements of the stack
traversal() void display()
{
1. if top = -1 if(top==-1)
1.print “stack empty” {
2. else
1. for(i = top; i >= 0;i--) printf("\n stack is empty(underflow)");
1.print “stack[i]” return
3.endif }
4. stop printf("\n the elements in stack are:\n");
for(i=top;i>=0;i--)
printf("->%d",stack[i]);
}
If the top value is -1 then the stack is empty.

If the stack is not empty, assign a top value to variable i, display the item
which is pointed at stack[i] , decrement the top value by one and repeat this
process until top becomes zero.

C program example1 , also show error simulation


Dr.L.Lakshmi 12 12
STACK ADT USING LINKED LIST
STACK IMPLEMENTATION USING LINKED LIST

 Implementing stacks as linked lists provides a feasibility on the number of nodes by


dynamically growing stacks, as a linked list is a dynamic data structure.

 The stack can grow or shrink as the program demands it to.

 Disadvantage of using an array to implement a stack or queue is the wastage of


space.

 A variable top always points to top element of the stack.

 top = NULL specifies stack is empty.

Dr.L.Lakshmi 13 13
STACK ADT USING LINKED LIST
Example:
 The following list consists of five cells, each of which holds a data object
and a link to another cell.

Dr.L.Lakshmi 14 14
STACK ADT USING LINKED LIST
Push function POP function
void push() void pop()
{ {
struct node*temp; struct node*temp;
temp=(struct node*)malloc(sizeof(struct if(top==NULL)
node)); printf("\n stack is empty \n");
printf("\n enter data of item:"); else
scanf("%d",&temp->data); {
temp->link=top; temp=top;
top=temp; printf("popped item is %d \
} n",temp->data);
top=top->link;
free(temp);
}
}

Dr.L.Lakshmi 15 15
STACK ADT USING LINKED LIST
Traversal function

void display()
{
struct node*temp;
temp=top;
if(top==NULL)
printf("stack is empty \n");
else
{
printf("stack elements:\n");
while(temp!=NULL)
{
printf("->%d",temp->data);
temp=temp->link;
}
}
}
C program example2 , also show error simulation
Dr.L.Lakshmi 16
STACK APPLICATIONS

APPLICATIONS

• Stacks are used in conversion of infix to postfix expression.

• Stacks are also used in evaluation of postfix expression.

• Stacks are used to implement recursive procedures.

• Stacks are used in compiler design.

Dr.L.Lakshmi 17 17
STACK APPLICATIONS

TYPES OF EXPRESSIONS

Arithmetic expressions can be represented in three ways:

Infix notation: The operator is in between the two operands.


Examples: A+B 2+3

Prefix (Polish notation): The operator precedes the operands.


Examples: +AB +23

Postfix (Reverse Polish Notation): The operator follows the operands.


Examples: AB+ 23+

Dr.L.Lakshmi 18 18
STACK APPLICATIONS

CONVERSIONS

Consider the infix expression: 2 + 3 * (5 – 7) / 9


Let us insert implicit parentheses
(2 + ((3 * (5 – 7)) / 9))

Transfer the operators to the beginning of parentheses


(+ 2 (/ (* 3 (– 5 7)) 9))
Remove the parentheses: + 2 / * 3 – 5 7 9
This is the equivalent prefix expression.

Transfer the operators to the end of parentheses


(2 ((3 (5 7 –) *) 9 /) +)
Remove the parentheses: 2 3 5 7 – * 9 / +
This is the equivalent postfix expression.

Dr.L.Lakshmi 19 19
STACK APPLICATIONS
Algorithm to convert infix expression to Postfix:
1.Initialize an empty stack.
2.Repeat the following process until the end of the infix expression.

Get next input token (constant, variable, arithmetic operator, left
parenthesis, right parenthesis) in the infix expression.

If the token is

A left parenthesis: Push it onto the stack.

A right parenthesis:

Pop and display stack elements until a left parenthesis is on the top of
the stack.

Pop the left parenthesis also, but do not display it.

An operator:

While the stack is nonempty and token has higher or equal priority than
the stack’s top element, pop and display.

Push token onto the stack.

An operand: Display it.
3.When the infix expression is reached to the end, pop and display stack items
until the stack is empty.
(Note: Left parenthesis in the stack has lowest priority)
Dr.L.Lakshmi 20 20
STACK APPLICATIONS

Dr.L.Lakshmi 21 21
STACK ADT
1. Algorithm for postfix conversion:
void postfix(char inf[15])
Step 1: repeat the steps a to c until inf[i]!='\0'
a. check if infix expression is opening brace push it onto stack
check if(inf[i]='(‘) push(inf[i])
b. check if infix expression is alphabetic character add it to postfix express
if(isalpha(inf[i])) pf[j++]=inf[i]
c. check if infix expression is closing brace
if(inf[i]==')')
repeat 1 to 2 until stack[top]!=opening brace
1.pf[j++]=pop()
2.x=pop()
Otherwise
repeat 1 to 2 until prec(stack[top])>=prec(inf[i])
1.pf[j++]=pop()
2.push(inf[i])
Step 2: repeat the steps a to b until top!=-1
a.pf[j++]=pop()
b.pf[j]='\0'
step 3: stop
Dr.L.Lakshmi 22 22
STACK ADT
2. Algorithm for push operation on stack:
Step 1:increment top by 1
Step 2: stack[++top]=y
Step 3:stop

3. Algorithm for pop operation on stack:


Step 1:return stack[top]
Step 2: decrement top by 1
Step 3:stop

4. Algorithm for finding precedence of operators :


Step 1:check if (c=='*' || c=='/' || c=='%')
return(5)
step 2:check if (c=='+' || c=='-')
return(3)
Step 3:if(c=='(')
return(1)
step 4:stop

Dr.L.Lakshmi 23 23
STACK ADT

5. Algorithm for main function :


Step 1:start
Step 2: read infix expression
Step 3:call postfix(infix)
Step 4:print postfix expression result
Step 5:stop

Dr.L.Lakshmi 24 24
STACK APPLICATIONS
Postfix conversion function

void postfix(char inf[15]) else


{ {
char x; while(prec(stack[top]>=prec(inf[i])))
for(i=0;inf[i]!='\0';i++) pf[j++]=pop();
{ push(inf[i]);
if(inf[i]=='(') }
push(inf[i]);
else if(isalpha(inf[i])) }//end of for
pf[j++]=inf[i]; while(top!=-1)
else if(inf[i]==')') {
{ pf[j++]=pop();
while(stack[top]!='(') pf[j]='\0';
pf[j++]=pop(); }//end of postfix()
x=pop(); }
}
void push(int y) int pop()
{ {
stack[++top]=y; return(stack[top--]);
}//end of push() }//end of pop()
Dr.L.Lakshmi 25
STACK APPLICATIONS
recedence function

int prec(char c)
{
if(c=='*' || c=='/')
return(5);
else if(c=='+' || c=='-')
return(3);
else if(c=='(')
return(1);
}//end of prec()

C program example3 , also show error simulation


Dr.L.Lakshmi 26
STACK APPLICATIONS

Algorithm to evaluate Postfix Expression:


1.Initialize an empty stack.
2.Do

Get next token (constant, arithmetic operator) in postfix expression.

If token is an operand, push it on the stack.

If token is an operator do the following:

Pop top two values from the stack. (If the stack does not contain two items,
report error.)

Apply operator token to these two values.

Push the resulting value onto the stack.
3.Continue the process until the end of the expression is encountered.
4.The value of the expression is on the top of the stack (and stack should
contain only this value).

Dr.L.Lakshmi 27 27
STACK APPLICATIONS

C program example4 , also show error simulation


Dr.L.Lakshmi 28 28
STACK APPLICATIONS
Postfix evaluation function case '-':push(a-b);
void evaluate(char pf[15]) break;
{ case '*':push(a*b);
float a,b,x; break;
for(i=0;pf[i]!='\0';i++) case '/':push(a/b);
{ break;
if(isalpha(pf[i])) default: printf("invalid operator\n");
{ }//end of switch
printf("enter value of %c",pf[i]); }//end of else
scanf("%f",&x); }//end of for
push(x); printf("value of expression %f",stack[top--]);
}//end of if }//end of evaluate()
else//if operator
{ void push(float y)
b=pop(); {
a=pop(); stack[++top]=y;
switch(pf[i]) }
{ float pop()
case '+':push(a+b); {
break; return(stack[top--]);
Dr.L.Lakshmi 29
}
STACKS

Applications of Stacks

• Direct applications

Page-visited history in a Web browser

Undo sequence in a text editor

Chain of method calls in the Java Virtual Machine
• Indirect applications

Auxiliary data structure for algorithms

Component of other data structures

Dr.L.Lakshmi 30 30
STACK APPLICATIONS
Demonstration of Manual infix to postfix conversion

Step 1 A + B * C by placing paranthesis results


(A+( B* C) )
Step 2 moves the multiply operator after C
( A + (B C *) )

moves the addition operator to between the last two closing parentheses. This
change is made because the closing parentheses for the plus sign is the last
parenthesis.
We now have ( A ( B C * ) + )

Finally ,step 3 removes the parentheses A B C * +

Dr.L.Lakshmi 31
STACK APPLICATIONS
Infix Transformations
A + B * C – D / E Converts to A B C * + D E / -
Above transformation is illustrated in following figure.

Example 4 converting infixDr.L.Lakshmi


expression to postfix expression 32
STACK APPLICATIONS

Evaluation of Postfix Expression


• In evaluation of postfix expression, it is the operands that are pushed on to the
stack. The postfix expression is scanned from left to right. Any operands
encountered are pushed on to the stack. When an operator is encountered, the
top two operands are popped from the stack. The operation is performed and
the result is pushed back on to the stack. In the end, the final value is popped
from the stack and returned.

Dr.L.Lakshmi 33
STACK APPLICATIONS
Evaluation of Postfix Expression
For example given expression is A B C + *
And assuming that A is 2, B is 4, and C is 6 ,
the following figure shows the evaluation of postfix expression.

Example 5 evaluation of postfix expression


Dr.L.Lakshmi 34
Queues
Definition
• A queue is a order / linear list in which data can be inserted at one end, called
the rear, and deleted from the other end, called the front. It is a first in–first
out (FIFO) restricted data structure.
• A queue is same as
Ex: 1)a line of people waiting for a bus at bus station.
2)a list of waiting jobs to be processes by a computer.
• The fig-1 below shows two examples of a queue.
A) A queue of people
B) a computer queue

Dr.L.Lakshmi
35 35
Queues

ADT Queue is
Object: a finite ordered list with 0 / more elements.
Functions:
for all queue belong Queue, item belong element, maxQueueSize belongs positive
integer.
Queue Create(maxQueueSize)::= create an empty queue whose maximum size is
maxQueueSize
Boolean IsFull(queue ,maxQueueSize)::=
if (number of elements in queue == maxQueueSize) return TRUE else return
FALSE
Queue AddQ(queue , item) ::=
if (IsFullQ(queue)) queueFull else insert item at rear of queue and return queue
Boolean IsEmptyQ(queue) ::=
if (queue == CreateQ(maxQueueSize)) return TRUE else return FALSE
Element DeleteQ(queue) ::=
if (IsEmptyQ(queue)) return else remove and return the item at front of queue
Dr.L.Lakshmi
36 36
Queues

• Linear list.
• One end is called front.
• Other end is called rear.
• Additions are done at the rear only.
• Removals are made from the front only.

Dr.L.Lakshmi 37
Bus Stop Queue

Bus
Stop

front rear rear rear rear


rear

Dr.L.Lakshmi 38
Bus Stop Queue

Bus
Stop

front rear rear


rear

Dr.L.Lakshmi 39
Bus Stop Queue

Bus
Stop

front rear
rear

Dr.L.Lakshmi 40
Bus Stop Queue

Bus
Stop

front rear
rear

Dr.L.Lakshmi 41
Revisit Of Stack Applications
• Applications in which the stack cannot be
replaced with a queue.
1. Parentheses matching.
2. Towers of Hanoi.
3. Switchbox routing.
4. Method invocation and return.
5. Try-catch-throw implementation.

• Application in which the stack may be replaced


with a queue.
1. Rat in a maze.
• 2. Results in finding shortest path to exit.
Dr.L.Lakshmi 42
Queues

Objectives:

Queue Operations
Queue Linked List Design
Queue Functions
Queue Demonstration

Dr.L.Lakshmi
43 43
Queues

Queue operations:

The two basic queue operations:


1)Insertion operation (enqueue)
2)Deletion operation (dqueue)


Data can be inserted at the rare in queue

Data can be deleted at front in queue

Dr.L.Lakshmi
44 44
QUEUE ADT
IMPLEMENTATION
Queue can be implemented in two ways:
1. using arrays
2. using linked list

Dr.L.Lakshmi 45 45
Queues using arrays
• We can also implement queue using arrays.
• There are mainly two functions in implementation of queue:
1) enqueue
2) dequeue
Enqueue
• An enqueue to an empty queue is placed in the first element of the array.
which becomes both front and rear.
• Subsequent enqueues are placed at the array locations following rear i.e if the
last element is stored at array location 11,the data for next enqueue is placed
in element 12.

Dr.L.Lakshmi
46 46
Queues using arrays
Dequeue
• A dequeue takes place at the front of the queue.
• As an element is deleted from the queue, the queue front is advanced to the next
location
• Fig-8 shows about physical structure of queue

Queue ary
count Max size front rare

7 17 5 11

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15]

FIG-8 Physical structure

Dr.L.Lakshmi
47 47
QUEUE USING ARRAY

Adding / enqueu function


1 if(rear==SIZE-1)
2 print queue is full / overflow
3 return;
4 else
5 rear++;
6 enter the element to ENQUEUE
7 if(front==-1)
8 front++;
Dr.L.Lakshmi 48 48
QUEUE USING ARRAY

Deleting /dequeue function


1. if(front==-1)
2. print queue is empty / underflow
3. return;
4. else
5. print the DEQUEUE element arr[front]
6. if(front==rear)
7. front=rear=-1
8. else
9. front++
Dr.L.Lakshmi 49 49
QUEUE USING ARRAY
displayfunction

1.if(front==-1)
2. print queue is empty / underflow
3. return;
4. print the element in queue are
5. for(i=front;i<=rear;i++)
6. print arr[i]

Dr.L.Lakshmi 50 50
Queues using arrays
Disavantages:
• In a queue, we delete elements at front and insert elements at rear.
• when rear reaches maximum size of an array, we can’t Insert new element though we
have space at front end of a queue.
• Therefore queue is not full because there are empty elements at the beginning of the
array. It shows queue is full.
• Fig shows array queue with last elements filled

Queue Queue
front rare

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]
[12]

 Fig array queue with last elements filled

Example -7 Dr.L.Lakshmi
for 51
queue using array 51
Queues Linked List

• There two basic functions in queue using linked list


1) Enqueue
2) Dequeue
Enqueue
• when we insert data into a queue, the queue’s front and rear pointers must be
set to the new node
• When we insert data into a queue with data already in it, we must point both
the link field in the last node and rear pointer to the new node.
• If insert is successful, it returns true else if no memory left for the new node, it
returns false
• Fig shows enqueue

Dr.L.Lakshmi
52 52
Queues Linked List

Dequeue

• If the queue is empty, we have underflow and return false

• We first ensure that the queue contains data.

• If the queue contains data, then set the front pointer to the next
item in the queue

• If we dequeue the last item, the queue front pointer


automatically becomes null pointer. it also assigns null pointer
to link filed of the last node.

• Fig shows dequeue implementation.


Dr.L.Lakshmi
53 53
Queues Linked List

FIGURE -6 Enqueue Example


Dr.L.Lakshmi
54 54
QUEUE USING LINKED LIST
struct node
{
int data;
struct node*link;
};
struct node*front=NULL,*rear=NULL;

Dr.L.Lakshmi 55 55
QUEUE USING LINKED LIST

Enqueue function

1. struct node *temp


2. temp=(struct node*)malloc(sizeof(struct node))
3. print enter the element to be inserted
4. temp->data=ele
5. temp->link=NULL
6. if(rear==NULL||front==NULL)
7. front=temp
8. else
9. rear->link=temp
10. rear=temp
Dr.L.Lakshmi 56 56
QUEUE USING LINKED LIST

Dequeue function

1. struct node*temp;
2. if(front==NULL||rear==NULL)
3. print queue underflow
4. else
5. temp=front;
6. print deleted element temp->data
7. front=front->link
8. free(temp)

Dr.L.Lakshmi 57 57
QUEUE USING LINKED LIST

Display function

1. struct node *temp


2.temp=front
3. if(front==NULL||rear==NULL)
4. print queue is empty
5. else
6. while(temp!=NULL)
7. print temp->data
8. temp=temp->link
Example -6 for queue using linked list

Dr.L.Lakshmi 58 58
Queues Linked List

FIGURE -7 Dequeue Examples

Dr.L.Lakshmi
59 59
Circular Queues
• This disadvantage is overcome by shifting all the elements from end to the
beginning of the array
• In the above example, we shift from element 5 to 0 and 6 to 1 and so on.
• A more efficient alternative is found in circular queue
• In a circular queue, the last element is logically followed by the first element

Dr.L.Lakshmi
60 60
Circular Queues
Circular queue can be implemented in two ways

1.Circular queue using arrays


2.Circular queue using linked lists

Dr.L.Lakshmi 61
Circular Queues
Circular queue using arrays

Insertion into the circular queue

[2] [3]
Initially circular queue is
empty

front= -1 [1] [4]


rear= -1

[0] [5]

Dr.L.Lakshmi 62
Circular Queues

front=0 and rear=0 front=0 and rear=1

Dr.L.Lakshmi 63
Circular Queues

front=0 and rear=2 front=0 and rear=3

Dr.L.Lakshmi 64
Circular Queues

front=0 and rear=4 front=0 and rear=5

Dr.L.Lakshmi 65
Circular Queues
Circular queue using arrays

Deletion from the circular queue

front=1 and rear=5 front=2 and rear=5

Dr.L.Lakshmi 66
Circular Queues

front=3 and rear=5 Front=4 and rear=5

Dr.L.Lakshmi 67
Circular Queues
Circular queue using arrays

Insertion from the circular queue

front=4 and rear=0 front=4 and rear=1


Dr.L.Lakshmi 68
Circular Queues

front=4 and rear=2 front=4 and rear=3

Dr.L.Lakshmi 69
Circular Queue

Insert an element into a Circular Queue


if(front ==(rear+1)%MAXSIZE)
printf("\n\nCIRCULAR QUEUE IS OVERFLOW");
else
{
if(front==-1)
front=rear=0;
else
rear=(rear+1)%MAXSIZE;
cqueue[rear]=item;
}

Dr.L.Lakshmi
70 70
Circular Queue

Delete an element from a circular queue

if(front == -1)
printf("\n\nCIRCULAR QUEUE IS UNDERFLOW");
else
{
a=cqueue[front];
if(front==rear)
front=rear=-1;
else
front = (front+1)%MAXSIZE;
printf("\n\nDELETED ELEMENT FROM QUEUE IS : %d ",a);
}

Dr.L.Lakshmi
71 71
Circular Queue

Display the content of a circular queue

if(front == -1)
printf("\n\nCIRCULAR QUEUE IS UNDERFLOW");
else
{
for(i=front;i<=rear;i++)
{
printf(“ %d \t“,cqueue[i]);
}
}

Dr.L.Lakshmi 72
Circular Queue

Insert an element into a Circular Queue using linked list


void enqueue()
{
struct node*temp;
temp=(struct node*)malloc(sizeof(struct node));
printf("\n enter the element to be inserted");
scanf("%d",&temp->data);
temp->link=NULL;
if(count==0)
front=temp;
else
rear->link=temp;
rear=temp;
rear->link=front;
count++;
}
Dr.L.Lakshmi 73
Circular Queue
Delete an element from a circular queue
void dequeue()
{
struct node*temp;
if(front==NULL||rear==NULL)
printf("\n queue underflow");
else
{ count--;
if(front==rear)
{ printf("\n deleted element is %d",front->data);
free(front);
front=rear=NULL;
} else
{ temp=front;
printf("\n deleted element is %d\n",temp->data);
front=front->link;
rear->link=front;
free(temp);
}}}
Dr.L.Lakshmi 74
Circular Queue
Display the content of a circular queue
void display()
{
int i; struct node*temp;
if(front==NULL||rear==NULL)
printf("\n queue is empty");
else
{
if(count==0)
printf("\n queue is empty");
else
{
temp=front;
for(i=0;i<count;i++)
{
printf("->%d",temp->data);
temp=temp->link;
}
printf(")\n");
} } } Dr.L.Lakshmi 75
DEQUEUE
A double-ended queue is an abstract data type similar to an simple queue, it allows
you to insert and delete from both sides means items can be added or deleted
from the front or rear end.

Dr.L.Lakshmi 76 76
DEQUEUE

• A Deque or deck is a double-ended queue.


• Allows elements to be added or removed on either the
ends.

Dr.L.Lakshmi 77
DEQUEUE

TYPES OF DEQUE
 Input restricted Deque
• Elements can be inserted only at one end.

• Elements can be removed from both the ends.

 Output restricted Deque


• Elements can be removed only at one end.

• Elements can be inserted from both the ends.


Dr.L.Lakshmi 78
DEQUEUE

Deque as Stack and Queue


As STACK
• When insertion and deletion is made at the same side.

As Queue
• When items are inserted at one end and removed at the other
end.

Dr.L.Lakshmi 79
DEQUEUE

Dequeue is also called as double ended queue and it allows user to perform
insertion and deletion from the front and rear position. And it can be easily
implemented using doubly linked list. On creating dequeue, we need to add two
special nodes at the ends of the doubly linked list(head and tail). And these two
nodes needs to be linked between each other(initially).

head tail
--------------------------- --------------------------------
| | | ---|---------->| | | |
| NULL | 0 | | | | 0 | NULL |
| | | |<----------|--- | | |
---------------------------- -------------------------------

Dr.L.Lakshmi 80 80
DEQUEUE
So, the header node goes before the first node of the queue and the trailer node
goes after the last node in the queue. To do insertion at the front position, place
the new node next to the head. And to do insertion at the rear position, place the
new node before the tail. Similarly, dequeue operation can also be performed at
the front and rear positions.

Operations
Insert a New Element From front
Insert a New Element From rear
Delete an Element From front
Delete an Element From rear

Dr.L.Lakshmi 81 81
DEQUEUE using Array
1. Algorithm for insertion at rear end:

Step 1: check if(front==-1)


front++
rear++
read the element to insert a[rear]
count++;
Step 2: check if(rear>=SIZE-1)
print Insertion is not possible, overflow!!!
return
Step 3: Increment the rear by 1
read the element to insert a[rear]
count++;
Step 4:stop

Dr.L.Lakshmi 82 82
DEQUEUE using Array
2. Algorithm for insertion at front end:

Step 1: check if(front==-1)


front++
rear++
read the element to insert a[rear]
count++
Step 2: check if(rear>=SIZE-1)
print Insertion is not possible, overflow!!!
return
Step 3: Repeat the steps a to d until i>0
a[i]=a[i-1]
read the element to insert a[i]
count++
rear++;
Step 4:stop

Dr.L.Lakshmi 83 83
DEQUEUE using Array
3. Algorithm for deletion at rear end:

Step 1: check if (front==-1)


Print Deletion is not possible: Dequeue is empty
return
Step 2: otherwise
Print The deleted element is a[rear]
Check if(front==rear)
front=rear=-1
otherwise
rear=rear-1
Step 3:stop

Dr.L.Lakshmi 84 84
DEQUEUE using Array
Algorithm for deletion at front end:

1: check if (front==-1)
Print Deletion is not possible: Dequeue is empty
return
Step 2: otherwise
Print The deleted element is a[front]
Check if(front==rear)
front=rear=-1
otherwise
front=front-1
Step 3:stop

5.Algorithm for displaying the dequeue:

Step 1: check if (front==-1)


Print Dequeue is empty
return
Step 2: otherwise
Repeat step a until i<=rear (i=front)
Print a[i] Dr.L.Lakshmi 85 85
Step 3:stop
DEQUEUE using Linked list
ALGORITHM:
Initialize the front and rear nodes with NULL values
struct node *front=NULL,*rear=NULL,*cur,*temp

1. Algorithm for insertion at rear end:

Step 1: Create a new node


cur=(struct node*) malloc (sizeof (struct node))
Step 2: Read the content of node (cur->data)
Step 3: Assign new node right link to NULL
cur->right=NULL
Step 4: Assign new node to front & rear node
Check if(rear==NULL&&front==NULL)
rear=front=cur
Step 5: otherwise
rear->right=cur
cur->left=rear
rear=cur
Step 6:stop
Dr.L.Lakshmi 86 86
DEQUEUE using Linked list
2. Algorithm for insertion at front end:

Step 1: Create a new node


cur=(struct node*) malloc (sizeof (struct node))
Step 2: Read the content of node (cur->data)
Step 3: Assign new node right link to NULL
cur->right=NULL
Step 4: Assign new node to front & rear node
Check if(rear==NULL&&front==NULL)
rear=front=cur
Step 5: otherwise
cur->right=front
front->left=cur
front=cur
Step 6:stop

Dr.L.Lakshmi 87 87
DEQUEUE using Linked list
3. Algorithm for deletion at front end:

Step 1: check if(front==NULL)


Print deQueue is empty
Step 2: otherwise
Check if(front==rear)
Print Deleted data is front->data
front=rear=NULL
Step 3: otherwise
temp=front;
print Deleted data is temp->data
front=front->right
front->left=NULL
free(temp)
Step 4: stop

Dr.L.Lakshmi 88 88
DEQUEUE using Linked list
4. Algorithm for deletion at rear end:

Step 1: check if(front==NULL)


Print deQueue is empty
Step 2: otherwise
Check if(front==rear)
Print Deleted data is rear->data
front=rear=NULL
Step 3: otherwise
temp=rear;
print Deleted data is temp->data
if(front==rear)
front=rear=NULL
rear=rear->left
rear->right=NULL
free(temp)
Step 4: stop

Dr.L.Lakshmi 89 89
DEQUEUE using Linked list
5.Algorithm for displaying the dequeue:

Step 1: check if(front==NULL)


Print deQueue is empty
Step 2: otherwise
temp=front;
repeat steps a-b until temp!= NULL
a. printf("<-%d ->",temp->data)
b. temp=temp->right;

Step 3: stop

Dr.L.Lakshmi 90 90
APPLICATIONS OF DEQUE

Palindrome-checker

Dr.L.Lakshmi 91
APPLICATIONS OF DEQUE

A-Steal job scheduling algorithm


• The A-Steal algorithm implements task scheduling for several

• processors(multiprocessor scheduling).
• The processor gets the first element from the deque.

• When one of the processor completes execution of its own


threads
• it can steal a thread from another processor.
• It gets the last element from the deque of another processor and
• executes it.
Dr.L.Lakshmi 92
APPLICATIONS OF DEQUE

OTHER APPLICATIONS OF DEQUE

• Undo-Redo operations in Software applications.

Dr.L.Lakshmi 93
End

Dr.L.Lakshmi 94

You might also like