Stacks & Queues
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Stack
Non-primitive linear data structure. Ordered list where addition and deletion of an existing data item is done at one end called top. Last-in first-out (LIFO) data structure.
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Stack Creation,Insertion & Deletion
top top top top top top
Stack empty [just created]
A
Insert A
B A
Insert B
C B A
Insert C
D C B A
Insert D
E D C B A
Insert E Stack full
top
D C B A
Delete
top
C B A
Delete
top
B A
Delete
top
A
Delete
top Delete
Stack empty
Stack has five elements capacity. size=5
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
If attempted to add new element beyond the maximum size, stack full condition is encountered. Stack empty condition is reached ,if tried to remove the elements beyond the base of the stack PUSH: to add an element in stack POP: to delete an element from stack
Preeti S. Patil Introduction to Data structure MPSTME, SHIRPUR
Representation of Stacks
Represented using
Static [Using Arrays] Dynamic [Using Linked List]
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Static Representation
Created as
int stack[ MAXSIZE ] Where MAXSIZE is the maximum number of elements.
Define macro,MAXSIZE with appropriate value as
#define MAXSIZE 10
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Operations on stack
Operations
1. PUSH 2. POP 3. TOP
4.stack_empty
Description
This adds(pushes) a new element This deletes the data item from the top of the stack. It returns the value of the item at the top of the stack. It returns true if the stack is empty. Otherwise it returns false It returns true if the stack is full. Otherwise it returns false.
Introduction to Data structure MPSTME, SHIRPUR
Restriction
The number of data items on the stack should not exceed MAXSIZE The number of data item on the stack should not go beyond Zero.
5. Stack_full
Preeti S. Patil
Push Operation
Push (int stack[],int MAXSIZE,int top) { int item; if(top==(MAXSIZE-1)) /*Check for overflow*/ { printf( stack is full); return; } else { printf( Enter the element to be inserted); scanf(%d,&item); top=top+1; /* increment top*/ stack[top] = item; /* insert item*/ } }
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Pop Operation
pop (int stack[ ], int top) { int item; if(top == -1) /* underflow */ { printf(stack is empty); return; } else { item= stack[top]; /* delete item*/ top= top-1; } return(item); }
Preeti S. Patil Introduction to Data structure MPSTME, SHIRPUR
Applications of Stack
To keep track of function calls. In conversion of arithmetic expressions into any form.
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Illustration of Function calls
Consider following c program #include<stdio.h> main() { int i=10, j; j= funct1(i); printf( %d,j); } /* End of Main*/ funct1(int k) { int m=20, n; n= funct2(m); printf(%d,n); }
/* End of funct1()*/
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
funct2(int x) { int y,z;; y= x+10; z= funct3(y); return(z); } funct3( int a) { int b; b=a*5; return(b); }
/* End of funct2()*/
/*End of funct3*/
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Illustration of function call
Funct2() Funct1() Main() Initial stack Funct1() called Main() Funct2() called Funct1() Main() Funct3() called
Funct1() Main() Funct3() completes Main() Funct2() completes Funct1() completes
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Arithmetic Expression
Expression which involves addition, subtraction, multiplication and division operations. There are three ways of writing arithmetic expressions.
Infix Postfix Prefix
Preeti S. Patil Introduction to Data structure MPSTME, SHIRPUR
Infix Expression
Arithmetic operator exists in between two operands. Usual notation of writing mathematical expressions.
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Example: Infix Expression
Eg 1: let A & B are two operands then infix form of expression for arithmetic operators +, -, * & / are as A+B A-B A*B A/B Eg 2: if A , B & C are three operands, then we can write the infix form as (A + B) C (A + (B * C) (A / B) + C Note: In infix form of expression, parenthesis impose a precedence (priority) of operation.
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Postfix
It is the form of an arithmetic expression in which, arithmetic operator is fixed (place) after (post) its operands. Called as suffix notation. Referred even as reverse polish notation.
Preeti S. Patil Introduction to Data structure MPSTME, SHIRPUR
Eg 1: let A & B are two operands then postfix form of expression for arithmetic operators +, -, * & / are as
INFIX FORM A+B A-B A*B A/B POSTFIX FORM AB+ ABAB* AB/
Eg 2: if A , B & C are three operands, then we can write the postfix form as INFIX FORM POSTFIX FORM A+B*C ABC*+ A+BC AB + C(A + B) * C AB + C*
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Rules that govern the evaluation of Arithmetic expression Precedence of arithmetic expression
Operation Exponential Operators ^ Precedence Highest
Multiplication / Division Addition / Subtraction
*, /
Next
+,-
Last
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Rules that govern the evaluation of Arithmetic expression contd
Is evaluated from left to right. Exponential operation is evaluated from right to left. In C, We have no exclusive exponential operator. We use ^ as an exponential operators Parenthesized expression is evaluated FIRST.
Preeti S. Patil Introduction to Data structure MPSTME, SHIRPUR
Examples
Eg 1: Consider A+B*C Steps to convert to postfix form. A + (B C *) A (B C *) + ABC*+
Introduction to Data structure MPSTME, SHIRPUR
Preeti S. Patil
Ex: 5+(4-3)*8 1. Convert 4-3 into postfix and store it in T T= 4 32. Then the expression becomes 5+T*8 3. Convert T* 8 into postfix and store it in S S= T8* 4. Then the expression becomes 5+S 5. Now convert the expression 5+S into postfix and substitute the value for S 5(T8*)+ 6. Substitute the value of T in the expression and the result will be as 5((43-)8*)+ 7. Finally the resultant postfix 543-8*+
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Prefix Notation
It is form of arithmetic expression, in which we fix (place) the arithmetic operator before (pre) its operands. Also called polish notation.
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Examples
Eg 1: let A & B are two operands then postfix form of expression for arithmetic operators +, -, * & / are as
INFIX FORM A+B A-B A*B A/B A^B PREFIX FORM +AB -AB *AB /AB ^AB
Eg 2: if A , B & C are three operands, then we can write the postfix form as INFIX FORM PREFIX FORM A+B*C +A*BC A+BC -+ABC (3 + 4) * (8 - 9) *+34-89 X / Y ^Z +A +/X ^ YZA
Preeti S. Patil Introduction to Data structure MPSTME, SHIRPUR
Convert infix to prefix.
Procedure
1. Apply the rules that govern the evaluation of arithmetic expression. 2. Go on placing the corresponding operator before its two operands.
Ex : Convert the infix expression to prefix. A*B+C/D
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Steps to convert infix to prefix
Given Infix Expression A*B+C/D Convert A * B to prefix form and store it in T. i.e., T = *AB Then, The expression becomes T + C/D convert C/D to prefix form and store it in S i.e. S = /CD Then, the Expression becomes T+S Now, convert this expression to prefix form and store it in R i.e. R = +TS So, R will contain the result, that is. R = +((*AB)(/CD)) (Parenthesis not convenience) = +*AB/CD (After removing parenthesis)
Introduction to Data structure MPSTME, SHIRPUR
3.
4.
Preeti S. Patil
Conversion from Infix to Postfix
Assumptions:
Only single character (letter or digit) operands are allowed. Only +, -, * ,^ and / operators are considered. Unary minus is excluded. Expression is error-free.
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Algorithm Infix to postfix
1. 2. Scan the infix expression from left to right. a) if the scanned symbol is left parentheses, push it onto the stack. b) if the scanned symbol is an operand, then place directly in the postfix expression. c) if the scanned symbol is a right parentheses, then go on popping all the items from the stack and place them in postfix expression till we get the matching left parentheses. d) if 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 equal to the precedence of the scanned operator. Otherwise, push the scanned operator onto the stack.
Preeti S. Patil Introduction to Data structure MPSTME, SHIRPUR
Consider infix expression A+B*C Steps of evaluation to postfix as follows Action Scan A Scan + Scan B Scan * Scan C All symbols are over Symbol A + B * C Nil Stack Empty + + +* +* Nil Postfix expn A A AB AB ABC ABC*+ Description Place it on the postfix Push + onto the stack Place it on the postfix *has precedence over + so push onto the top of the stack. Straight away place C in the postfix expression. popout all operators from the stack and place them in the postfix.
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Program for infix to postfix conversion
#include<stdio.h> #include<string.h> int index=0, pos=0,top=-1, length; char symbol, temp; char infix[20],postfix[20],stack[20]; void main() { clrscr(); printf(Enter the infix expression); scanf(%s,infix); Infix_to_postfix(infix,postfix); printf(Infix expression is =%s\n,infix); printf(postfix expression= %s \n,postfix); getch(); }
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
infix_to_postfix (char infix[ ], char postfix[ ]) { length = strlen(infix); push(#); while (index < length) { symbol = infix[index]; switch (symbol) { case ( : push (symbol); break; case ): temp=pop(); while( temp != () { postfix[pos]=temp; pos++; temp=pop(); } break; case +: case -:
Preeti S. Patil Introduction to Data structure MPSTME, SHIRPUR
case *: case/: case^: while (preced (stack[top])>=preced(symbol)) { temp=pop(); postfix [pos] =temp; pos++; } push (symbol); break; default : postfix[pos++]=symbol; break; } index++; } while top>0) { temp=pop(); postfix [pos++]=temp; } return; }
Preeti S. Patil Introduction to Data structure MPSTME, SHIRPUR
push (char symb) { top=top+1; stack[top]=symb; return; } pop() { char symb; symb=stack[top]; top=top-1; return (symb); }
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
int preced (char symb) { int p; switch(symb) { case ^ : p=3; break; case * : case / : p=2; break; case +: case - : p=1; break; case ): case( : p=0; break; case #: p=-1; break; return(p); }
Preeti S. Patil Introduction to Data structure MPSTME, SHIRPUR
Output for the program
Enter the infix expression: A+B*C Infix expression is = A + B * C The postfix expression is ABC*+
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Convert these infix expression to postfix form
(A*B)+(C-D) ((A/B)/C)+D (A+B)*(C-D)/E-F (A-B)/C*((C-D/C+D)) A^B^C*D (A+B)*D+E/(F+G+D) A+B^C/D
Introduction to Data structure MPSTME, SHIRPUR
Preeti S. Patil
Evaluation of postfix expression
1. Store the numeric values corresponding
to each operand, in an array. 2. Scan the given postfix expression from LEFT to RIGHT
a. If the scanned symbol is an operand (variable name), then push its value onto the stack. b. If the scanned symbol is an operator, then pop out two values from the stack and assign them respectively to operand2 and operand 1.
3. Then perform the required arithmetic operation.
Preeti S. Patil Introduction to Data structure MPSTME, SHIRPUR
Algorithm contd
case operator of * : result = operand 1 * operand 2 / : result = operand 1 / operand 2 + : result = operand 1 + operand 2 - : result = operand 1 + operand 2 end case 4. Push the result onto the stack 5. Repeat steps 1 to 4 until all the symbols in the postfix expression are over.
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Algorithm in c evaluate suffix expression
float eval_suffix (char suffix[],float data[]) { int i=0; float op1,op2,res; char ch; while(suffix[i] != \0) { ch= suffix[i]; if(isalpha (suffix[i])) push (data[i]); else { op2= pop(); op1= pop();
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
switch(ch) { case + : push(op1 + op2); break; case - : push (op1 op2); break; case * : push (op1 * op2); break; case / : push (op1/op2); break; case ^ : push (pow(op1,op2)); break; } } i++; } res=pop(); return(res); }
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Ex: Infix: A+B*C Postfix: ABC*+ Values: A=2.0,B=3.0, and C=1.0
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Action Scan A
Symbol Stack A
2.0
Oper 1 -
Oper 2 -
Result -
Description Push As value into the stack
Push Bs value into the stack
Scan B
2.0
3.0
Scan C
C
2.0 3.0 1.0
Push Cs value into the stack
Pop 2 immediate values and assign them to operand 2 and operand 1 and evaluate.then push result back Onto the stack Pop 2 immediate values and assign them to operand 2 and operand 1 and perform addition then store result back onto the stack
Scan *
2.0
3.0
3.0
1.0
3.0
Scan +
+
5.0
2.0
3.0
5.0
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Pop out the stack content, value 5.0 is the result.
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
End of Topic
Stacks
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Queues
A queue is a non primitive linear data structure. Ordered homogeneous group of elements in which elements are added at one end called rear. Deletion is done from other end called front.
Preeti S. Patil Introduction to Data structure MPSTME, SHIRPUR
First element added to the queue is the first one to be removed from the queue. Often called First In First Out (FIFO) data structure.
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Front end 10
20
30
40
50
60
Rear end
Capacity =6, size=6. Element 10 is the first element to be removed Element 60 is last element to be deleted.
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Representation of a Queue
Static representation using arrays. Dynamic representation using linked list. Array representation of a queue needs two indices. FRONT and REAR. Array declaration in C is as follows int queue [MAXSIZE];
Preeti S. Patil Introduction to Data structure MPSTME, SHIRPUR
Conditions to be assumed
FRONT=REAR, if the queue is empty. Therefore the initial condition of a queue is
FRONT=REAR=-1
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Operations on a Queue
Operation
1. Create Queue
Description
It creates a new empty queue. This operation must be carried out in order to make the queue logically accessible It inserts a new data item at the rear of the queue It deletes and then return the data item at the front of the queue. It returns true if the queue is full. Otherwise it returns false. It returns true if the queue is empty. Otherwise it returns false.
Restriction
-
2. Qinsert 3. Qdelete
Queue must not be full Queue must not be empty
4. Queue full
5. Queue Empty
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Algorithms for Queue operations
Front and rear are assigned value -1.
1. Qinsert
Inserts a new data item at the rear end of a queue. Qinsert(int Q[ ],int MAXSIZE, int FRONT, int item) { if (REAR>=MAXSIZE-1) /* overflow condition*/ { printf(Queue is full); return; } REAR=REAR+1; /* increment rear pointer */ Q[REAR]=item; /* insert data item */ if(FRONT==-1) /* check for proper setting of front pointer*/ FRONT=0; }
Preeti S. Patil Introduction to Data structure MPSTME, SHIRPUR
Algorithms contd
Qdelete
This operation deletes and returns the data item at the front of the queue. Qdelete(int Q[ ], int FRONT,int REAR, int item) { if(FRONT==-1) { printf(Queue is empty); /* underflow condition*/ return; } item=Q [FRONT]; if(FRONT=REAR) FRONT=REAR=-1; else FRONT=FRONT+1; return (item); }
Preeti S. Patil Introduction to Data structure MPSTME, SHIRPUR
Consider a queue which can hold maximum 4 elements, initially it is empty.
Empty Queue FRONT=REAR=-1 F R
Insert 10 to the queue. Then queue status will be 10 F R R=R+1
Next, Insert 20 to the queue. Then queue status will be 10 F 20 R R=R+1 F=0
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Again, Insert another element 30 to the queue. The queue status is 10 F 20 30 R R=R+1
Let us delete an element. Remember that the element at the FRONT is the candidate for removal. So, the status of queue would be 20 F 30 R
F=F+1
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Again, delete an element.The element to be deleted is always pointed by FRONT pointer. So,, 20 is deleted. therefore, the status of queue would be 30 F R Now, Insert a new element 40 in the queue. Then queue status will be F=F+1
30 F
40 R
R=R+1
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Next insert another element,say,50 to the queue. You cannot add 50 to the queue as the rear crossed the maximum size of a queue (i.e 4) there will be Queue full signal. Thus the status is shown below.
30 F
40 R
R=R+1
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
DeQue
Homogeneous list of elements in which insertion and deletion operations are performed from both the ends. Called as double ended queue.
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Types of Deque.
Types are due to the restriction put to perform either the insertions or deletions only at one end. Two Types
Input-restricted deque. Output-restricted deque. Deque with 5 elements.
FRONT REAR
Deletion Insertion
10 Dq[0]
20 Dq[1]
30 Dq[2]
40 Dq[3]
50 Dq[4]
Insertion Deletion
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Algorithms to perform operations on Deque
Operations on DeQue
1. Insertion of an element at the REAR end of the queue. 2. Deletion of an element from the FRONT end of the queue. 3. Insertion of an element at the FRONT end of the queue. 4. Deletion of an element from the REAR end of the queue.
Note: 2,3, & 4 are valid operations for input restricted deque. 1,2,& 3 are valid operations for output restricted deque.
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
An input-restricted deque is one where deletion can be made from both ends, but insertion can only be made at one end. An output-restricted deque is one where insertion can be made at both ends, but deletion can be made from one end only.
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
1. Insertion of an element at the rear end of the queue.
DQinsert_Rear(int Q[ ],int FRONT,int REAR, int item, int MAXSIZE) { if(REAR==(MAXSIZE -1)) /*overflow*/ { printf(Queue is full); return; } REAR=REAR+1; /* increment rear by 1*/ Q[REAR] = item; /* insert element into Q*/ }
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
2. Deletion of an element from the FRONT end of the queue DQdelete_Front(int Q[ ], int FRONT, int REAR, int item) { if(FRONT==REAR) /* is Q Empty*/ { printf(Queue is empty); return; } item= Q[FRONT]; /*delete element into Q*/ FRONT=FRONT+1; /*increment FRONT*/ }
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
3. Insertion of an element at the Front end of the queue. DQInsert_Front(int Q[ ], int FRONT, int REAR,int item) { if(FRONT== 0) { printf(Queue is full); return; } /* decrement FRONT*/ FRONT=FRONT-1; Q[FRONT]=item; /*Insert element*/ }
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
4. Deletion of an element from the REAR end of the queue. DQdelete_Rear(int Q[ ],int FRONT, int REAR,int item) { if(FRONT==REAR==-1) { printf(Queue is empty); return; } item=Q[item]; /*Delete element*/ REAR=REAR-1; /*Decrement Rear*/ }
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
5. Algorithm to display the elements of Queue. void DQ_display(int Q[ ],int FRONT, int REAR) { if(FRONT <= REAR) { printf(status of the queue\n); for(i=FRONT;i<=REAR; i++) { printf(%d,DQ[i]); } else printf(Queue is empty); } }
Preeti S. Patil Introduction to Data structure MPSTME, SHIRPUR
Circular queue
There are some problems associated with the ordinary queues
Time consuming Signaling queue even if the queue is actually empty.
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Front end 10
20
30
40
50
60
Rear end
Now if we delete all the 6 elements from the queue, at the end of those deletions the value of front would become 6. In this situation, if we attempt to insert a new data item to the queue, we would receive queue full message, even though queue is not full. This problem is overcome by implementing Circular queue.
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
In circular queue, if we reach the end while inserting elements to it, it is possible to insert new elements if the slots at the beginning of the circular queue are empty. FRONT and REAR are used to keep track of the elements to be deleted and inserted respectively. Each time the new element is inserted into the queue the variable REAR is incremented by one. Similarly each time an item is deleted from the queue, the variable front is incremented by one.
Preeti S. Patil Introduction to Data structure MPSTME, SHIRPUR
Front 5 CQ[0] 10 CQ[1]
Rear 25 CQ[2] CQ[3] CQ[4]
insert an element 32.so the status would be
Front 5 CQ[0] 10 CQ[1] 25 CQ[2] Rear 32
REAR=(REAR+1)%5
CQ[3]
CQ[4]
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Again insert element 50, so the rear is incremented by 1 and 50 is put in that position. Then the status of the queue will be.
Front 5 CQ[0] 10 CQ[1] 25 CQ[2] 32 CQ[3] Rear 50
REAR=(REAR+1)%5
CQ[4]
If we insert a new element to the queue . The next position of the FRONT where the element is going to be inserted is computed using modulus operator.
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Here Rear=4 REAR=(REAR+1)%5 =0 Therefore, REAR will be pointing to CQ[0]. And, FRONT is also pointing to CQ[0]. Since FRONT=REAR, the queue is full. So we cannot add the element.
Preeti S. Patil
Introduction to Data structure MPSTME, SHIRPUR
Algorithm to insert an element into a circular queue Void Cqinsert(int Q, int FRONT, int REAR, int Item, int MAXSIZE) { if (FRONT==(REAR+1)%MAXSIZE) /* queue overflow*/ printf(queue is full); return; } if(FRONT==-1) FRONT=REAR=0; else REAR=(REAR+1)%MAXSIZE; /* insert item*/ Q[REAR]=item; }
Preeti S. Patil Introduction to Data structure MPSTME, SHIRPUR
Algorithm to delete an item from circular queue Int CQDelete(int Q[], int FRONT, int REAR, int item,) { if(FRONT==-1) /* under flow condition*/ { printf(queue is Empty); return; } item=Q[FRONT]; /* is queue empty*/ If(FRONT==REAR) FRONT= REAR=-1; else FRONT=(FRONT+1)%MAXSIZE; }
Preeti S. Patil Introduction to Data structure MPSTME, SHIRPUR
Priority Queues
Collection of elements such that each element has been assigned a priority Elements are deleted and processed based on following
An element of higher priority is processed before any element of lower priority. Two elements with the same priority are processed according to the order in which they were added to the queue.
Preeti S. Patil Introduction to Data structure MPSTME, SHIRPUR