0% found this document useful (0 votes)
22 views23 pages

Unit 2 Bca Sem III Cam205 2c Dsa

Uploaded by

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

Unit 2 Bca Sem III Cam205 2c Dsa

Uploaded by

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

BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

BCA Semester – III (Second Year)


Data Structures and Algorithms
CAM205-2C (Major)
Unit 2

Stack
A stack is an ordered, collection of homogeneous data element where the insertion and
deletion operations take place at one end only i.e., data is stored and retrieved in a Last In
First Out (LIFO) order. Stack is a linear data structure and very much useful in various
applications of computer science.

 The insertion and deletion operations in case of stack are specially termed as PUSH and
POP respectively and the position of the stack where these operations are performed is
known as TOP of the stack.
 An element in a stack is termed as ITEM. The maximum number elements that a stack
can accommodate are termed as SIZE.

OPERATIONS ON STACK
There are four operations of Stack as follows:
1. Push (Insertion)
2. Pop (Deletion)
3. Peep (Free Space)
4. Change (Update Value)

Page 1 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

1. Algorithm for PUSH operation


Input: The new ITEM to be pushed onto it.
Output: A stack with newly published ITEM at the TOP position
Data structure: An array A with TOP as the pointer.
Steps:
1. [Check for stack overflow]
If top = size -1 then
Print “ Stack is full”
Exit
2. [Increment top pointer by one]
Top = Top + 1
3. [Perform Insertion]
Stack [Top] = value
4. Stop

2. Algorithm for POP operation


Input: A stack with elements.
Output: Removes an ITEM from the top of the stack if it is not empty.
Data structure: An array A with TOP as the pointer.
Steps:
1. [Check for stack underflow]
If top = -1
Print “Stack is empty”
Exit
2. [Remove the top information]
Value = stack[top]
Top = top – 1
3. Stop

Page 2 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

Applications of Stack
1. Evaluation of Arithmetic Expressions:
There are three notations to represent an arithmetic expression:
 Infix Notation
 Prefix Notation
 Postfix Notation
2. Backtracking Algorithms: Backtracking is another application of Stack. It is a recursive
algorithm that is used for solving the optimization problem.
3. Processing Function Calls: Stack plays an important role in programs that call several
functions in succession.
4. Undo/Redo operations: The undo-redo feature in various applications uses stacks to keep
track of the previous actions.
5. Browser history: Web browsers use stacks to keep track of the web pages you visit.

Application of Stack in real life:


 CD/DVD stand.
 Stack of books in a book shop.
 Call centre systems.
 Undo and Redo mechanism in text editors.
 The history of a web browser is stored in the form of a stack.
 Call logs, E-mails, and Google photos in any gallery are also stored in form of a
stack.
 YouTube downloads and Notifications are also shown in LIFO format (the latest
appears first).

1. Evaluation of Arithmetic Expressions


An arithmetic expression consists of operands and operators. Operands are variables or
constants and operators are of various types like arithmetic unary and binary operators
[for example, - (unary), + (addition), - (subtraction), * (multiplication), / (division), ^
(exponentiation), % (remainder modulo), etc], relational operators (for example, <, >, <=,
<>, >=, etc), and Boolean operators (such as, AND, OR, NOT, XOR, etc). In addition to
these, parenthesis ‘(‘ and ‘)’ are also used.

A+B*C/D–E^F*G

Page 3 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

The problem to evaluate this expression is the order of evaluation. There are two ways to
fix it. We can assign precedence/priority to each operator.

Symbols Priority
( ) 4 (Highest Priority)
$ ^ 3
* / 2
- + 1(Lowest Priority)

Notations for arithmetic expressions


1. Infix (x + y)
The conventional (usual) way of writing an expression is infix. This is called infix because
the operators come in between the operands.
2. Prefix ( + xy)
When operator precedes two operands, it is called prefix notation. This notation was
introduced by Polish mathematician Jan Lukasiewicz and hence also termed as polish
notation.
3. Postfix ( xy+ )
When operator follows two operands is called postfix or reverse polish notation.

Conversion of an expressions from Infix to Prefix


1. A ^ B * C – D + E / F / (G + H)
A ^ B * C – D + E / F / +GH
^AB * C – D + E / F / +GH
*^ABC – D + E / F / +GH
*^ABC – D + /EF / +GH
*^ABC – D + //EF+GH
-*^ABCD + //EF+GH
+-*^ABCD//EF+GH

Page 4 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

2. A – B + C ^ D ^ E / F * G + H
A – B + ^CD ^ E / F * G + H
A – B + ^^CDE / F * G + H
A – B + /^^CDEF *G + H
A – B + */^^CDEFG + H
-AB + */^^CDEFG + H
+-AB*/^^CDEFG + H
++-AB*/^^CDEFGH

3. (A + B) * (C ^ (D – E) + F) – G
+AB * (C ^ -DE + F) – G
+AB * (^C-DE + F) – G
+AB * +^C-DEF – G
*+AB+^C-DEF – G
-*+AB+^C-DEFG

4. A + B * C * D / E / F ^ G + H
A + B * C * D / E / ^FG + H
A + *BC * D / E / ^FG + H
A + **BCD / E / ^FG + H
A + /**BCDE / ^FG + H
A + //**BCDE^FG + H
+A//**BCDE^FG + H
++A//**BCDE^FGH

5. ((A + B) * C – (D – E)) $ (F + G)
(+AB * C – (D – E)) $ (F + G)
(+AB * C - -DE) $ (F + G)
(*+ABC - -DE) $ +FG
-*+ABC-DE $ +FG

Page 5 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

$-*+ABC-DE+FG

Conversion of an expressions from Infix to Postfix

1. (A + ((B ^ C) – D)) * (E – (A/C))


(A + (BC^ – D)) * (E – AC/)
(A + BC^D-) * (EAC/-)
ABC^D-+ * EAC/-
ABC^D-+EAC/-*

2. A + B * C * D / E / F ^ G + H
A + B * C * D / E / FG^ + H
A + BC* * D / E / FG^ + H
A + BC*D* / E / FG^ + H
A + BC*D*E/ / FG^ + H
A + BC*D*E/FG^/ + H
ABC*D*E/FG^/+ + H
ABC*D*E/FG^/+H+

3. A $ B * C – D + E / F / (G + H)
AB$ * C – D + E / F / GH+
AB$C* - D + E / F / GH+
AB$C* - D + EF/ / GH+
AB$C* - D + EF/GH+/
AB$C*D- + EF/GH+/
AB$C*D-EF/GH+/+

Page 6 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

Algorithm of Converting an Expression from Infix to Postfix


Optstack: Stack of operators
Infix: Infix expressions
Postfix: Postfix expression
Steps:
1. Scan the symbol of infix array one by one from left to right.
2. If symbol is ‘(‘ left parenthesis than add it to the optstack.
3. If symbol is operand than add it to the postfix array.
4. a. if symbol is operator than POP the operator which have same precedence or higher
precedence then the operator which occurred.
b. add popped operator to postfix array.
c. add the scan symbol operator into opt stack.
5. a. If symbol is “)’ right parenthesis, POP all the operators from optstack until ‘(’ left
parenthesis in optstack.
b. Remove left parenthesis from optstack.
6. When there is no symbol remains in infix array than POP all the symbols from optstack
and add them to postfix array.

Examples:

1. Infix: a + ( b + c ) – d

Infixarray:
a + ( b + c ) - d

Postfixarray:

a b c + + d -

Postfix: abc++d–

Page 7 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

2. Infix: (A + ((B ^ C) – D)) * (E – (A / C))


Infixarray:

( A + ( ( B ^ C ) - D ) ) * ( E - ( A / C ) )

Postfixarray:

A B C ^ D - + E A C / - *

Postfix: ABC^D-+EAC/-*

3. Infix: a * (b + c * d) – e / f
Infixarray:

a * ( b + c * d ) - e / f

Postfixarray:

a b c d * + * e f / -
Postfix: a b c d * + *e f / -

Page 8 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

Evaluation of Postfix Expression


Examples:
1. 2 3 + 2 4 ^ - 3 + Ans : -8

2. 6 2 3 + - 3 8 2 / + * 2 ^ 3 +  Ans = 52

4. 1 2 3 5 4 - + ^ * 2 3 * -  Ans:10

Page 9 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

2. Write a program of Stack with PUSH, POP, PEEP and CHANGE Operations.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define size 5

int stack[size],value,top=-1,newval, pos;

void push();
void pop();
void peep();
void change();
void display();

void main()
{
int ch;
clrscr();
while(1)
{
printf("\n*******Stack Program******");
printf("\n1.PUSH");
printf("\n2.POP");
printf("\n3.PEEP");
printf(“\n4.CHANGE”);
printf("\n5.DISPLAY");
printf("\n6.EXIT");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:push();break;
case 2:pop();break;
case 3:peep();break;
case 4:change();break;
case 5:display();break;
case 6:exit(0);break;
default:printf("\nWrong choice");
}
}
}
void push()
{
if(top==(size-1))
{
printf("\nStack is FULL");
}
else
{

Page 10 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

top=top+1;
printf("\nEnter value:");
scanf("%d",&value);
stack[top]=value;
}

}
void pop()
{
if(top==-1)
printf("\nStack is Empty");
else
{
value=stack[top];
printf("\nPopped item is %d",value);
top=top-1;
}
}
void peep()
{
int freespace;
freespace=(size-1)-top;
printf("\nFree Space in stack is %d",freespace);
}
void display()
{
int i;
for(i=top;i>=0;i--)
{
printf("\n|%d|",stack[i]);
printf("\n___");
}
}
Void change()
{
Printf(“\nEnter position:”);
Scanf(“%d”,&pos);
Printf(“\nEnter new value for change:”);
Scanf(“%d”,&newval);
Stack[pos]=newval;
}

Queues
A queue is a linear list of elements in which deletions can take place only at one end, called
the front, and insertions can take place only at the other end, called the rear.

Page 11 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

 In computer implementation, there is an example of accessing the printer in multi user


environment. If the printer is in process and more than one user wants to access the
printer then it maintains the queue for requesting user and serves as first in first out
manner, means give access permission to the user which comes first in the queue.

Representation of Queue using Array


With this representation, two pointers, namely, FRONT and REAR are used to indicate two
ends of the queue. For the insertion of the next element, pointer REAR will be used and for
deletion pointer FRONT will be used.

TYPES OF QUEUES
1. Simple Queue
2. Circular Queue
3. Double Ended Queue
4. Priority Queue

1. Simple Queue
Queues are also called first-in-first-out (FIFO) lists, since the first element in a queue will
be the first element out of the queue. In other words, the order in which elements enter a
queue is the order in which they leave. This contrasts with stacks, which are last-in-first-out
(LIFO) lists. The only difference between stack and queue is that in that case of stack,
insertion and deletion (PUSH and POP) operations are at one end Top only, but in case of
queue insertion (called Enqueue) and deletion (called Dequeue) operations take place at
two ends called rear and front of the queue respectively.
Elements in a queue are termed as ITEM; the number of elements that a queue can
accommodate is termed as length.
Now let us define the operation ENQUEUE to insert an element into a queue.

Page 12 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

Algorithm ENQUEUE (ITEM)


Input: An element ITEM that has to be inserted.
Output: The ITEM is at the REAR of the queue.
Data structure: Q is the array representation of queue structure; two pointers FRONT and
REAR of the queue Q are known.
Steps:
1. If (REAR = SIZE-1) then // Queue is full
Print “Queue is full”
Exit
2. Else
If (FRONT = -1) and (REAR = -1) // Queue is empty
FRONT = 0
endif
REAR = REAR + 1 // Insertion of ITEM
Q[REAR] = ITEM
3. EndIf
4. Stop

Algorithm DEQUEUE()
Input: A dequeue with elements. FRONT and REAR are the two pointers of the queue.
Output: The deleted element is stored in ITEM.
Data structures: Q is the array representation of queue structure; two pointers FRONT and
REAR of the queue Q are known.

Steps:
1. If (FRONT = -1) then
Print “Queue is empty”
Exit
2. Else

Page 13 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

ITEM = Q[FRONT] // deleted ITEM


If (FRONT = REAR)
FRONT = REAR = -1
Else
FRONT = FRONT + 1
EndIf
3. Endif
4. Stop

Disadvantage of simple queue


There is one potential problem with this representation. With this representation, a queue
may not be full, still a request for insertion operation may lead to a problem. If REAR = N
and FRONT = SIZE, then all rooms are empty till REAR – 1. But the problem is that if
REAR has reached to at the end of queue means (REAR = SIZE-1) then we can’t insert any
new element. Though we have empty rooms we can’t insert any new element, so this is a
simply a wastage of the storage.

2. Circular Queue

As the problem we faced in simple queues that if the REAR reaches at the end then
insertion will be not possible, though we have space at the front position. So the left
blocks(means rooms) is one type of wastage because we can’t insert any new ITEM in it.

Now, to overcome this drawback, we have circular queue. In it, if the REAR reaches at the
end also, and if blocks/space (rooms) are available than REAR will be send at the starting
point.

Algorithm ENCQUEUE (ITEM)


Input: An element ITEM to be inserted into the circular queue.
Output: Circular queue with the ITEM at FRONT, if the queue is not full.
Data structure: CQ be the array to represent the circular queue. Two pointers FRONT and
REAR are known.
Steps:

Page 14 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

1. (FRONT == 0 && REAR==(SIZE-1)) || (FRONT==REAR+1)


Print “Circular queue is full”
Exit
2. else
If (FRONT==-1 && REAR==-1)
Then
FRONT=0
REAR=0
Else
If(REAR==(SIZE-1))
Then
REAR=0
Else
REAR=REAR+1
Endif
endif
2. CQ[REAR] = ITEM
3. EndIf
4. Stop

Algorithm DECQUEUE()
Input: A queue CQ with elements. Two pointers FRONT and REAR are known.
Output: The deleted element is ITEM if the queue is not empty.
Data structure: CQ is the array representation of circular queue.

Steps:
1. If (FRONT == -1) then
Print “Queue is Empty”
Exit
2. Else
Item = CQ [FRONT]

Page 15 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

If (FRONT == REAR)
FRONT = REAR = -1
` Else
If (FRONT==(SIZE-1)) then
FRONT=0
Else
FRONT=FRONT+1
Endif
EndIf
3. EndIf
4. Stop

3. Double ended queue

A deque (pronounced either “deck” or “dequeue”) is a linear list in which elements can be
added or removed at either end but not in the middle. The term deque is a concentration of
the name double-ended queue.

Deque is maintained by a circular array DEQUE with pointers LEFT and RIGHT, which
point to the two ends of the deque. The elements extended from the left end to the right end
in the array. The term circular comes from the fact that DEQUEUE[1] comes after
DEQUEUE[N] in the array.

Four operations of Double Ended Queue:


1. Insert from Front/Left
2. Insert from Rear/Right
3. Delete from Front/Left
4. Delete from Rear/Right

4. Priority Queue

Page 16 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

A priority queue is another variation of queue structure. Here, each element has been
assigned a value, called priority of the element, and the element can be inserted or deleted
not only at the ends but at any position on the queue.
In a priority queue, each element has a priority value associated with it. When you add an
element to the queue, it is inserted in a position based on its priority value. For example, if
you add an element with a high priority value to a priority queue, it may be inserted near
the front of the queue, while an element with a low priority value may be inserted near the
back.

In above example, D can be deleted first, not the front. Here D’s priority is high so it can be
deleted first. Similarly, insertion of an element is based on its priority, that is, instead of
adding it after the rear, it may be inserted at an intermediate position dictated by its priority
value.

Applications of Queue

 Task Scheduling: Queues can be used to schedule tasks based on priority or the
order in which they were received.
 Resource Allocation: Queues can be used to manage and allocate resources, such as
printers or CPU processing time.
 Batch Processing: Queues can be used to handle batch processing jobs, such as data
analysis or image rendering.
 Message Buffering: Queues can be used to buffer messages in communication
systems, such as message queues in messaging systems or buffers in computer
networks.
 Event Handling: Queues can be used to handle events in event-driven systems, such
as GUI applications or simulation systems.
 CPU Scheduling: Job Queue, Ready Queue, Device Queue
In computer implementation, there is an example of accessing the printer in multi
user environment. If the printer is in process and more than one user wants to access
the printer then it maintains the queue for requesting user and serves as first in first
out manner, means give access permission to the user which comes first in the queue.

Page 17 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

3. Write a program of Simple Queue with Enqueue and Dequeue operations.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define size 5

int Q[size],f=-1,r=-1,value;

void enq();
void deq();
void display();

void main()
{
int ch;
clrscr();
while(1)
{
printf("\n******Simple Queue Program******");
printf("\n1.Enqueue");
printf("\n2.Dequeue");
printf("\n3.Display");
printf("\n4.Exit");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:enq();break;
case 2:deq();break;
case 3:display();break;
case 4:exit(0);break;
default:printf("\nWrong Choice");
}
}
}
void enq()
{
if(r==(size-1))
printf("\nQueue is FULL.......");
else
{
if(f==-1 && r==-1) // == means comparision operator
{
f=0; // = assignment operator
}
r=r+1;

Page 18 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

printf("\nEnter value:");
scanf("%d",&value);
Q[r]=value;
}
}
void deq()
{
if(f==-1)
printf("\nQueue is Empty.....");
else
{
value=Q[f];
printf("\nDequeued item is %d",value);
if(f==r)
f=r=-1;
else
f=f+1;
}
}
void display()
{
int i;
for(i=f;i<=r;i++)
printf("\t%d",Q[i]);
}

4. Write a program of Circular Queue with EnCqueue and DeCqueue operations.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define SIZE 5

void insert();
void del();
void display();

int CQ[SIZE];
int front = -1;
int rear = -1;

Page 19 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

void main()
{
int choice;
while(1)
{
printf("1.Insert\n");
printf("2.Delete\n");
printf("3.Display\n");
printf("4.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);

switch(choice)
{
case 1 :
insert();
break;
case 2 :
del();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice\n");
}/*End of switch*/
}/*End of while */
}/*End of main()*/

Page 20 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

void insert()
{
int item;
if((front == 0 && rear == SIZE-1) || (front == rear+1))
{
printf("Queue Overflow \n");
return;
}
else
{
if (front == -1) /*If queue is empty */
{
front = 0;
rear = 0;
}
else
{
if(rear == SIZE-1)/*rear is at last position of queue */
rear = 0;
else
rear = rear+1;
}
printf("Input the element for insertion in queue : ");
scanf("%d", &item);
CQ[rear] = item ;
}
}/*End of insert()*/

void del()

Page 21 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

{
if (front == -1)
{
printf("Queue Underflow\n");
return ;
}
printf("Element deleted from queue is : %d\n",CQ[front]);
if(front == rear) /* queue has only one element */
{
front = -1;
rear=-1;
}
else
{
if(front == SIZE-1)
front = 0;
else
front = front+1;
}
}/*End of del() */

void display()
{
int f=front,r=rear;
if(front==-1)
{
printf("Queue is empty\n");
return;
}
printf("Queue elements :\n");
if( f <= r )
{

Page 22 of 23
BCA Sem III - CAM205-2C DSA (Major) BPCCS & SVICS, Gandhinagar

while(f <= r)
{
printf("%d ",CQ[f]);
f++;
}
}
else
{
while(f <= SIZE-1)
{
printf("%d ",CQ[f]);
f++;
}
f = 0;
while(f <= r)
{
printf("%d ",CQ[f]);
f++;
}
}/*End of else */
}/*End of display()

Page 23 of 23

You might also like