10 DS Notes - Stack and Queue
10 DS Notes - Stack and Queue
void main()
{
int ch, size, value;
printf("Enter the size of stack : ");
scanf("%d",&size);
do
{
printf("\n 0. Exit");
printf("\n 1. Push ");
printf("\n 2. Pop ");
printf("\n 3. Peep");
printf("\n 4. Change");
printf("\n 5. Display");
printf("\n Enter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 0:
exit(0);
break;
case 1:
printf("\nEnter the element to be pushed : ");
scanf("%d", &value); 30
push(value, size);
display();
break;
case 2:
pop();
display();
break;
case 3:
peep();
display();
break;
case 4:
printf("\nEnter the tos to be changed : ");
scanf("%d",&value);
change(value);
S. V. Patel College Page | 3
By: Dr. Piyush Arora Data Structures using C
display();
break;
case 5:
display();
break;
default:
printf("\n Enter Proper choice \n");
}
}
while(ch != 0);
}
void push(int value, int size)
{
if(tos == size – 1)
{
printf("\n ---Stack overflow--- \n");
return;
}
else
{
tos = tos + 1;
stack[tos] = value;
}
}
void pop()
{
int x;
if(tos == -1)
{
printf("\n ---Stack Underflow--- \n");
return;
}
else
{
x = stack[tos];
tos = tos - 1;
printf(“Popped element = %d”, x);
}
}
void peep()
{
if(tos == -1)
{
printf("\n Stack is empty \n");
return;
}
else
{
printf("\n TOS = %d",stack[tos]);
}
}
void change(int value)
{
if(tos == -1)
{
printf("\n Stack is empty \n");
S. V. Patel College Page | 4
By: Dr. Piyush Arora Data Structures using C
return;
}
else
{
stack[tos] = value;
}
}
void display()
{
int i;
if(tos == -1)
{
printf("\n Stack is empty -- underflow \n");
return;
}
printf("\n Stack Elements: \n");
for(i=tos ; i>=0 ; i--)
{
printf("Element = %d \n",stack[i]);
}
}
Introduction:
There are three notations to represent arithmetic expressions (AE).
a. Infix notation: In this notation, the operator comes between the two operands.
<operand> <operator> <operand>
e.g.: A+B A*B A-B A/B A^B
b. Prefix notation OR Polish Notation: In this notation, the operator comes before the two operands.
<operator> <operand> <operand>
e.g.: +AB *AB -AB /AB ^AB
c. Postfix notation OR Reverse Polish Notation: In this notation, the operator comes after two operands.
<operand> <operand> <operator>
e.g.: AB+ AB* AB- AB/ AB^
Algorithm to convert Infix expression to Postfix expression / Infix to Reverse Polish Notation
Input: “E” is an arithmetic expression in infix notation.
Output: An arithmetic expression in postfix notation. It is stored in array and displayed in same manner.
Data Structure: One stack “s1” is used for push and pop operation.
Push(s1, x) means adding “x” to stack s1.
Push(s1, item) means adding an “item” to stack s1.
Pop(s1) means removing the top most element from the stack s1.
“item” is the symbol scanned.
“x” is the symbol popped from stack s1.
Scan_ch( ): The method used to scan one item from left to right.
Write(x): The method used to write the variable “x” in output expression.
Write(item): The method used to write the variable “item” in output expression.
Precedence( ): The method used to check the precedence of operators.
Step 1: [Initially add a right parenthesis “)” at the end of the infix expression E].
Step 2: [Push left parenthesis “(” on to the stack]
Push (s1, “(”)
Step 3: [Repeat steps 4 to 21 while stack s1 is not empty]
Step 4: [Scan the symbol from Infix Expression in left to right manner]
Set item = E.Scan_ch( )
Step 5: If (item == operand)
Step 6: [Write the symbol into output expression]
Write (item)
[End of step 5 if structure)]
Step 7: If (item == “(”)
Step 8: [Push symbol “(” into the stack s1]
Push(s1, item)
[End of step 7 if structure]
Step 9: If (item == operator)
Step 10: x = Pop(s1)
Step 11: If precedence (x) >= precedence (item)
Step 12: Repeat steps 13 and 14 while (precedence (x) >= precedence (item))
Step 13: Write (x)
Step 14: x = Pop(s1)
[End of step 12 loop]
[End of step 11 if structure]
Step 15: Push(s1, x)
Step 16: Push(s1, item)
[End of step 9 if structure]
Step 17: If (item == “)”)
Step 18: x = Pop(s1)
Step 19: Repeat steps 20 and 21 while x ≠ “(“
Step 20: Write (x)
Step 21: x = Pop(s1)
[End of step 19 loop]
[End of step 17 if structure]
[End of step 3 loop]
Step 22: Exit
Program to convert Infix expression to Postfix expression / Infix to Reverse Polish Notation
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<conio.h>
enum item_list{opernd, oper, leftbrack, rightbrack};
case oper:
if(stempty == 1)
{
push(item);
}
else
{
do
{
x = pop();
if(precedence(x) >= precedence(item))
{
post[k] = x;
k = k+1;
loop_yn=0;
}
else
{
loop_yn=1;
}
}
while((stempty==0) && (loopyn==0));
if(loopyn == 1)
{
push(x);
push(item);
}
else
{
push(item);
}
}
break;
case leftbrack:
S. V. Patel College Page | 11
By: Dr. Piyush Arora Data Structures using C
push(item);
break;
case rightbrack:
x=pop();
while(x != '(')
{
post[k] = x;
k = k+1;
x=pop();
}
break;
} // ---switch case complete---
++i;
}
while(top != -1)
{
post[k] = pop();
k = k+1;
}
void push(char c)
{
if(top == 100-1)
{
printf("\n Stack is Full");
stfull = 1;
return;
}
else
{
top=top+1;
stack[top] = c;
stempty = 0;
}
}
char pop()
{
char x;
if(top == -1)
{
stempty = 1;
x = ' '; // Used when -1 location is popped.
}
else
{
x = stack[top];
S. V. Patel College Page | 12
By: Dr. Piyush Arora Data Structures using C
top=top-1;
}
return(x);
}
Step 1: [Initially add a left parenthesis “(” at the beginning of the infix expression E].
Step 2: [Push right parenthesis “)” on to the stack s1]
Push (s1, “)”)
Step 3: [Repeat steps 4 to 21 while stack s1 is not empty]
Step 4: [Scan the symbol from Infix Expression “E” in right to left manner]
Set item = E.ReverseOrderScan_ch( )
Step 5: If (item == operand)
Step 6: [Push “item” into the stack s2]
Push(s2, item)
[End of step 5 if structure]
Step 7: If (item == “)”)
Step 8: [Push “item” into the stack s1]
Push(s1, item)
[End of step 7 if structure]
Step 9: If (item == operator)
Step 10: x = Pop(s1)
Step 11: If precedence (x) > precedence (item)
Step 12: Repeat steps 13 and 14 while (precedence (x) > precedence (item))
Step 13: Push(s2, x)
Step 14: x = Pop(s1)
[End of step 12 loop]
[End of step 11 if structure]
Step 15: Push (s1, x)
Step 16: Push (s1, item)
[End of step 9 if structure]
Step 17: If (item == “(“)
Step 18: x = Pop(s1)
Step 19: Repeat steps 20 and 21 while x ≠ “)”
Step 20: Push(s2, x)
Step 21: x = Pop(s1)
[End of step 19 loop]
[End of step 17 if structure]
[End of step 3 loop]
Step 22: [Repeat steps 23 and 24 while stack s2 is not empty]
Step 23: x = Pop(s2)
Step 24: Write(x)
[End of step 22 loop]
Step 25: Exit
S. V. Patel College Page | 14
By: Dr. Piyush Arora Data Structures using C
Example 1: Given “E”: A+((B*(C-D)^E)+F)/G
Append a left parenthesis at the beginning of the expression, so it looks like:
(A+((B*(C-D)^E)+F)/G
Symbol Stack (S1) Stack (S2) / Expression
)
G ) G
/ )/ G
) )/) G
F )/) GF
+ )/)+ GF
) )/)+) GF
E )/)+) GFE
^ )/)+)^ GFE
) )/)+)^) GFE
D )/)+)^) GFED
- )/)+)^)- GFED
C )/)+)^)- GFEDC
( )/)+)^ GFEDC-
* )/)+)* GFEDC-^
B )/)+)* GFEDC-^B
( )/)+ GFEDC-^B*
( )/ GFEDC-^B*+
+ )+ GFEDC-^B*+/
A )+ GFEDC-^B*+/A
( GFEDC-^B*+/A+
Finally pop all the elements from the stack S2, until it is empty.
Answer: +A/+*B^-CDEFG
while(end >= i)
{
loop_yn =1;
item=infix[end];
switch(symbol_type(item))
{
case opernd:
pre[k] = item;
k = k+1;
break;
case oper:
if(stempty)
{
push(item);
}
else
{
do
{
x = pop();
if(precedence(x) > precedence(item))
{
pre[k] = x;
k = k+1;
loop_yn =0;
}
else
{
loop_yn =1;
}
}
while((stempty == 0) && (loop_yn == 0));
if(loop_yn )
{
push(x);
push(item);
}
else
{
push(item);
}
}
break;
case leftbrack:
x=pop();
while(x != ')')
{
pre[k] = x;
k = k+1;
x=pop();
}
break;
} // ---switch case complete---
--end;
}
while(top != -1)
{
pre[k] = pop();
k = k+1;
}
void push(char c)
{
if(top == 100)
{
printf("\n Stack is Full");
stfull = 1;
return;
}
else
{
++top;
stack[top] = c;
stempty = 0;
}
}
char pop()
{
char item;
if(top == -1)
{
stempty = 1;
item = ' '; // used when -1 location is popped
}
else
{
S. V. Patel College Page | 19
By: Dr. Piyush Arora Data Structures using C
item = stack[top];
--top;
}
return(item);
}
int precedence(char c)
{
int priority;
switch(c)
{
case ')':
priority = 0;
break;
case '+':
case '-':
priority = 1;
break;
case '*':
case '/':
priority = 2;
break;
case '^':
priority = 3;
break;
}
return priority;
}
Step 1: [Initially add a right parenthesis “)” at the end of the postfix expression P].
Step 2: [Repeat steps 3 to 11 while item ≠ “)”]
Step 3: [Scan the symbol from “P” in left to right manner]
Set item = P.Scan_ch( )
Step 4: If (item == operand)
Step 5: [Operand is pushed into the stack]
Push(item)
[End of step 4 if structure]
Step 6: If (item == operator)
Step 7: [a is the second operand of the current operator]
Set a = Pop( ) a = -2
Step 8: [b is the first operand of the current operator]
Set b = Pop( ) b=2
Step 9: Set op = item op = *
Step 10: Set result = b op a
Step 11: push(result)
[End of step 6 if structure]
[End of step 2 loop]
Step 13: Set result = Pop( )
Step 14: Write result
Step 15: Exit
void main()
{
char post[100], item;
int i, len, val, val1, val2, val3;
//clrscr();
printf("Enter postfix notation : ");
gets(post);
len = strlen(post); len = 9
i=0;
while(i < len)
{
item = post[i];
switch(symbol_type(item))
{
case opernd:
printf("\n Enter the value of %c : ", item);
scanf("%d", &val);
push(val);
break;
case oper:
switch(item)
{
case '+':
val1 = pop();
val2 = pop();
val3 = val2 + val1;
push(val3);
break;
case '-':
val1 = pop();
val2 = pop();
val3 = val2 - val1;
push(val3);
break;
case '*':
val1 = pop();
val2 = pop();
val3 = val2 * val1;
push(val3);
break;
case '/':
val1 = pop();
val2 = pop();
val3 = val2 / val1;
push(val3);
break;
case '^':
val1 = pop();
val2 = pop();
val3 = pow(val2,val1);
push(val3);
S. V. Patel College Page | 22
By: Dr. Piyush Arora Data Structures using C
break;
}
break;
}
++i;
}
printf("\n Value of expression is : %d", pop());
}
int pop()
{
int p;
if(tos == -1)
{
printf("\n Stack is empty");
return 0;
}
else
{
p = stack[tos];
--tos;
return p;
}
}
int pop()
{
int p;
if(tos == -1)
{
printf("\n Stack is empty");
return 0;
}
else
{
p = stack[tos];
--tos;
return p;
}
}
Calls
f4( )
• When this function call occurs, they can be represented using stack, because the function calls are
maintained in LIFO order.
f3( )
f2( ) f2( ) f2( )
f1( ) f1( ) f1( ) f1( ) f1( ) f4( )
main( ) main( ) main( ) main( ) main( ) main( ) main( ) main( ) main( )
• To find the solution of a large problem, we can divide it into one or more sub-problems of a similar
nature, but smaller in size.
• We continue to find the solution of these sub-problems by dividing them again and again into smaller
sub-problems, until it reaches the simplest case.
• So, every recursive procedure can be divided into two parts:
o Base case: This is the smallest sub-problem obtained, which can be processed without
recursion. So, it tells us directly, what the answer is. There may be one or more than one base
cases.
o Recursive case: In this, we divide a particular problem into one or more sub-problems by
making progress towards the base case. There may be one or more than one recursive cases.
• Types of recursion:
a. Preemptive recursion: In this type of recursion, the function calls itself again and again.
e.g.: factorial, Hemachandra numbers or Fibonacci series, binary search, tower of Hanoi.
b. Non-preemptive recursion: In this type of recursion, the function becomes an argument in a call
of the function. e.g.: Ackerman’s function
• Note: Recursion cannot be used when we pass large amounts of data in the function. The execution
speed will decrease.
n*(n-1) if n > 0
• This can be represented as below, for n = 5:
5! = 5*(5-1)!
= 5*(4*4-1)!
= 5*(4*(3*3-1)!)
= 5*(4*(3*(2*2-1)!))
S. V. Patel College Page | 27
By: Dr. Piyush Arora Data Structures using C
= 5*(4*(3*(2*(1*1-1)!)))
= 5*(4*(3*(2*(1*(0!))))
= 5*(4*(3*(2*(1*1))))
= 5*(4*(3*(2*1)))
= 5*(4*(3*2))
= 5*(4*6)
= 5*24
= 120
Program to calculate factorial of a given number
#include<stdio.h>
#include<conio.h>
int fact(int n)
{
if(n == 0)
{
return 1;
}
else
{
return n * fact(n-1);
}
}
void main()
{
int n, f;
printf("Enter number to calculate factorial : ");
scanf("%d", &n); n = 5
f=fact(n);
printf("Factorial of %d is %d \n", n, f);
}
int fibo(int i)
{
if(i <= 0)
{
return 0;
}
else if(i == 1)
{
return 1;
}
else
{
return fibo(i-1) + fibo(i-2);
}
}
void main()
{
int n, i;
printf("Enter the no. of elements to be printed : ");
scanf("%d", &n);
for(i=0 ; i<n ; i++)
{
printf("%5d", fibo(i));
}
}
3. Binary Search
Program to search the element using binary search.
#include<stdio.h>
#include<conio.h>
if(key == a[mid])
{
return mid;
}
int main()
{
int a[30], n, i, ele, flag;
printf("\n Enter no. of elements : ");
scanf("%d", &n);
move(2, 1, 2, 3) 3 1 3 move(2, 2, 3, 1)
S T E T E S
S E T S E T
move(0, 1,2,3) 1 1 3 move(0, 2,3,1) move(0, 3,1,2) 1 3 2 move(0, 1,2,3) move(0, 2,3,1) 1 2 1 move(0, 3,1,2) move(0, 1,2,3) 1 1 3 move(0, 2,3,1)
STE TES STE TES STE TES STE TES
SET SET SET SET SET SET SET SET
0 1 2 3 4
5 10 15 20 25 No more insertion possible
Front = 0 Rear = 4 (Rear == SIZE – 1)
0 1 2 3 4
15 20 25 Deletion (Increment Front)
Front = 2 Rear = 4
0 1 2 3 4
25 (Front == Rear)
Front = 4 So, delete element and set
Rear = 4 Front = Rear = – 1
0 1 2 3 4
Front = -1 Set Front = Rear = – 1
Rear = -1
insert()
{
int ele;
if (rear == MAX - 1)
{
printf("\n Queue Overflow \n");
}
else
{
if (front == - 1) // First time only
{
front = 0;
}
printf("Input element for adding in queue : ");
scanf("%d", &ele);
rear = rear + 1;
queue[rear] = ele;
display();
}
}
del()
{
int ele;
if (front == - 1)
{
printf("\n Queue is Underflow \n");
return ;
}
else
S. V. Patel College Page | 35
By: Dr. Piyush Arora Data Structures using C
{
ele = queue[front];
if(front == rear)
{
front = -1;
rear = -1;
}
else
{
front = front + 1;
}
printf("Element deleted from queue : %d \n",ele);
display();
}
}
display()
{
int i;
if (front == - 1)
{
printf("Queue is empty\n");
}
else
{
printf("\n elements of Queue are :\n");
for (i = front; i <= rear; i++)
{
printf("%d ", queue[i]);
}
}
}
0 1 2 3 4
× 20 25
Insertion Front = 3 Rear = 4
Not
Possible
• We have one solution for this:
15
2
Physical Representation of Circular Queue Logical Representation of Circular Queue
3 20 1
3 1 3 20 10 1
Rear = 3
Rear = 3 15
15
2
2 2
Front = 2
While inserting first element, set While Deleting an element
Queue is empty Front = 0. Increment
Increment Front = (Front + 1) % SIZE
Rear = (Rear + 1) % SIZE
0
Rear = 0 Front = 4 Rear = 0 Front = 4 0
4 4 0 4
25 30 25 30 25 30
3 20 1 3 35 1
3 1
15 40
2 2 2
Front = 2 Rear = 2
Again, Insertion is possible at 0 Again , deletion is possible Again, Insertion is possible
Increment Increment Increment
Rear = (Rear + 1) % SIZE Front = (Front + 1) % SIZE Rear = (Rear + 1) % SIZE
0 1 2 3 4
5 10 15 Rear = Rear – 1
Front = 0 Rear = 2
0 1 2 3 4
15 20 25 Front = Front + 1
Front = 2 Rear = 4
0 1 2 3 4
15 20 25 Front = Front – 1
Front = 2 Rear = 4
Now “Queue is Overflow” on Left side,
0 1 2 3 4 When Front == 0
5 10 15 20 25 Similarly “Queue is Overflow” on Right Side,
Front = 0 Rear = 4 When Rear == SIZE – 1
Operations on DEQUE
insert_front(Q, value): To insert an element “value” in deque ‘Q’ using front pointer (at Left).
insert_rear(Q, value): To insert an element “value” in deque ‘Q’ using rear pointer (at Right).
delete_front(Q): To delete an element from deque ‘Q’ using front pointer (from Left).
delete_rear(Q): To delete an element from deque ‘Q’ using rear pointer (from Right).
Types of DEQUE
• There are two types of deque.
a. Input restricted DEQUE – In this deque, we can insert only at one end, but we can delete from
both the ends of the list.
So, we have algorithms to perform insertion at one end and deletion from both the ends.
b. Output restricted DEQUE – In this deque, we can delete only from one end, but we can insert at
both the ends of the list.
So, we have algorithms to perform deletion from one end and insertion at both the ends.
Note: It is up to the programmer to decide, at which end he wants to perform insertion and
deletion.
S. V. Patel College Page | 45
By: Dr. Piyush Arora Data Structures using C
Insert at Front 0 1 2 3 4
5 10 15 20 25
Delete from Front
Input Restricted from Right Delete from Rear
OR
0 1 2 3 4 Insert at Rear
5 10 15 20 25
Delete from Front Delete from Rear
Input Restricted from Left
Figure: Input Restricted DEQUE
Insert at Front 0 1 2 3 4 Insert at Rear
5 10 15 20 25
Delete from Rear
Output Restricted from Left
OR
Insert at Front 0 1 2 3 4 Insert at Rear
5 10 15 20 25
Delete from Front
Output Restricted from Right