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

BCA-302 - UNIT-II Notes

The document discusses stacks and queues. It defines a stack as a linear data structure where elements can only be inserted or removed from one end, called the top. Stacks follow the LIFO (last in, first out) principle. Common stack operations are push, which adds an element, and pop, which removes an element. Stacks have applications in arithmetic expression evaluation, backtracking, delimiter checking, and more. Queues are also discussed briefly as another linear data structure.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
147 views

BCA-302 - UNIT-II Notes

The document discusses stacks and queues. It defines a stack as a linear data structure where elements can only be inserted or removed from one end, called the top. Stacks follow the LIFO (last in, first out) principle. Common stack operations are push, which adds an element, and pop, which removes an element. Stacks have applications in arithmetic expression evaluation, backtracking, delimiter checking, and more. Queues are also discussed briefly as another linear data structure.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

UNIT-II

STACKS AND QUEUES

STACKS
A Stack is linear data structure. A stack is a list of elements in which an element may be
inserted or deleted only at one end, called the top of the stack. Stack principle is LIFO (last
in, first out). Which element inserted last on to the stack that element deleted first from the
stack.

As the items can be added or removed only from the top i.e. the last item to be added to a
stack is the first item to be removed.

Real life examples of stacks are:

Operations on stack:

The two basic operations associated with stacks are:


1. Push
2. Pop

While performing push and pop operations the following test must be conducted on the
stack.
a) Stack is empty or not b) stack is full or not

1. Push: Push operation is used to add new elements in to the stack. At the time of addition
first check the stack is full or not. If the stack is full it generates an error message "stack
overflow".

2. Pop: Pop operation is used to delete elements from the stack. At the time of deletion first
check the stack is empty or not. If the stack is empty it generates an error message "stack
underflow".

All insertions and deletions take place at the same end, so the last element added to the stack
will be the first element removed from the stack. When a stack is created, the stack base
remains fixed while the stack top changes as elements are added and removed. The most
accessible element is the top and the least accessible element is the bottom of the stack.

Representation of Stack (or) Implementation of stack:


The stack should be represented in two ways:
1. Stack using array
2. Stack using linked list

1. Stack using array:


Let us consider a stack with 6 elements capacity. This is called as the size of the stack. The
number of elements to be added should not exceed the maximum size of the stack. If we
attempt to add new element beyond the maximum size, we will encounter a stack overflow
condition. Similarly, you cannot remove elements beyond the base of the stack. If such is
the case, we will reach a stack underflow condition.

1. push():When an element is added to a stack, the operation is performed by push(). Below


Figure shows the creation of a stack and addition of elements using push().

Initially top=-1, we can insert an element in to the stack, increment the top value i.e
top=top+1. We can insert an element in to the stack first check the condition is stack is full
or not. i.e top>=size-1. Otherwise add the element in to the stack.

void push() Algorithm: Procedure for push():


{
int x; Step 1: START
if(top >= n-1) Step 2: if top>=size-1 then
{ Write “ Stack is
printf("\n\nStack Overflow” Step 3: Otherwise
Overflow.."); 3.1: read data value ‘x’
return; 3.2: top=top+1;
} 3.3: stack[top]=x;
else Step 4: END
{
printf("\n\nEnter data: ");
scanf("%d", &x);
stack[top] = x;
top = top + 1; printf("\n\
nData Pushed into the
stack");
}
}
1. Pop(): When an element is taken off from the stack, the operation is performed by pop().
Below figure shows a stack initially with three elements and shows the deletion of elements
using pop().

We can insert an element from the stack, decrement the top value i.e top=top-1.
We can delete an element from the stack first check the condition is stack is empty or not.
i.e top==-1. Otherwise remove the element from the stack.

Void pop() Algorithm: procedure pop():


{ Step 1: START
If(top==-1) Step 2: if top==-1 then
{ Write “Stack is
Printf(“Stack is Underflow”); Underflow” Step 3: otherwise
} 3.1: print “deleted element”
else 3.2: top=top-1;
{ Step 4: END
printf(“Delete data %d”,stack[top]);
top=top-1;
}
}

2. display(): This operation performed display the elements in the stack. We display the
element in the stack check the condition is stack is empty or not i.e top==-1.Otherwise
display the list of elements in the stack.
void display() Algorithm: procedure pop():
{ Step 1: START
If(top==-1) Step 2: if top==-1 then
{ Write “Stack is
Printf(“Stack is Underflow”); Underflow” Step 3: otherwise
} 3.1: print “Display elements are”
else 3.2: for top to 0
{ Print
printf(“Display elements are:); ‘stack[i]’ Step 4: END
for(i=top;i>=0;i--)
printf(“%d”,stack[i]);
}
}

Applications of stack:

1. Evaluation of Arithmetic Expressions


2. Backtracking
3. Delimiter Checking
4. Reverse a Data
5. Processing Function Calls

Application of Stack in real life:


 CD/DVD stand.
 Stack of books in a book shop.
 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 ).

Notations for Arithmetic Expression

There are three notations to represent an arithmetic expression:

 Infix Notation
 Prefix Notation
 Postfix Notation

Infix Notation

The infix notation is a convenient way of writing an expression in which each operator is placed
between the operands. Infix expressions can be parenthesized or unparenthesized depending upon
the problem requirement.
Example: A + B, (C - D)

All these expressions are in infix notation because the operator comes between the operands.

Prefix Notation

The prefix notation places the operator before the operands. This notation was introduced by the Polish
mathematician and hence often referred to as polish notation.

Example: + A B, -CD etc.

All these expressions are in prefix notation because the operator comes before the operands.

Postfix Notation

The postfix notation places the operator after the operands. This notation is just the reverse of Polish
notation and also known as Reverse Polish notation.

Example: AB +, CD+, etc.

All these expressions are in postfix notation because the operator comes after the operands.

Evaluation of Postfix Expressions Using Stack

Postfix expression is without parenthesis and can be evaluated as two operands and an operator at a time,
this becomes easier for the compiler and the computer to handle.

Evaluation rule of a Postfix Expression states:

1. While reading the expression from left to right, push the element in the stack if it is an operand.
2. Pop the two operands from the stack, if the element is an operator and then evaluate it.
3. Push back the result of the evaluation. Repeat it till the end of the expression.

Algorithm

1) Add ) to postfix expression.


2) Read postfix expression Left to Right until ) encountered
3) If operand is encountered, push it onto Stack
[End If]
4) If operator is encountered, Pop two elements
i) A = Top element
ii) B= Next to Top element
iii) Evaluate B operator A
push B operator A onto Stack
5) Set result = pop
6) END

Let's see an example to better understand the algorithm:

Expression: 456*+
Example 2. Evaluate 5,6,2+*12,4/-

Solution. append) at end 5,6,2+*12,4/- )

Symbol scanned Stack content


5 5
6 5,6
2 5,6,2
+ 5,8
* 40
12 40,12
4 40,12,4
/ 40,3
- 37
) 37

Result=37

Conversion of arithmetic expression

There are various types of conversion among expression

1. Infix to postfix
2. Infix to prefix
3. Postfix to prefix
4. Postfix to infix
5. Prefix to postfix
6. Prefix to infix

1. Infix to postfix

Algorithm to convert Infix To Postfix

Let, X is an arithmetic expression written in infix notation. This algorithm finds the equivalent postfix
expression Y.

1. Push “(“onto Stack, and add “)” to the end of X.


2. Scan X from left to right and repeat Step 3 to 6 for each element of X until the Stack is empty.
3. If an operand is encountered, add it to Y.
4. If a left parenthesis is encountered, push it onto Stack.
5. If an operator is encountered ,then:
1. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) which has the
same precedence as or higher precedence than operator.
2. Add operator to Stack.
[End of If]
6. If a right parenthesis is encountered ,then:
1. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) until a left
parenthesis is encountered.
2. Remove the left Parenthesis.
[End of If]
[End of If]
7. END.

Infix Expression: A+ (B*C-(D/E^F)*G)*H, where ^ is an exponential operator.

2. Infix to prefix

Infix to Prefix Conversion Algorithm

Iterate the given expression from right to left, one character at a time

Step 1: read given expression from right to left.


Step 2: If the scanned character is an operand, put it into prefix expression.
Step 3: If the scanned character is an operator and operator's stack is empty, push operator into
operators' stack.
Step 4: If the operator's stack is not empty, there may be following possibilities.
If the precedence of scanned operator is greater than the top most operator of operator's stack,
push this operator into operator 's stack.
If the precedence of scanned operator is less than the top most operator of operator's stack, pop the
operators from operator's stack untill we find a low precedence operator than the scanned character.

If the precedence of scanned operator is equal then check the associativity of the operator. If
associativity left to right then simply put into stack. If associativity right to left then pop the operators
from stack until we find a low precedence operator.

If the scanned character is opening round bracket ( '(' ), push it into operator's stack.

If the scanned character is closing round bracket ( ')' ), pop out operators from operator's stack
until we find an opening bracket ('(' ).

Repeat Step 2,3 and 4 till expression has character

Step 5: Now pop out all the remaining operators from the operator's stack and push into postfix
expression.
Step 6: Reverse the expression in step 5.
Step 7: Exit

Infix Expression: (A+B)+C-(D-E)^F


3. Postfix to prefix

Algorithm:
Iterate the given expression from left to right, one character at a time

1. If the character is operand, push it to stack.


2. If the character is operator,
1. Pop operand from the stack, say it’s s1.
2. Pop operand from the stack, say it’s s2.
3. perform (operator s2 s1) and push it to stack.
3. Once the expression iteration is completed, initialize the result string and pop out from the stack
and add it to the result.
4. Return the result.
4. Postfix to infix
5. Prefix to postfix

Algorithm:
Iterate the given expression from right to left, one character at a time

1. If the character is operand, push it to the stack.


2. If the character is operator,
1. Pop an operand from the stack, say it’s s1.
2. Pop an operand from the stack, say it’s s2.
3. perform (s1 s2 operator) and push it to stack.
3. Once the expression iteration is completed, initialize the result string and pop out from the stack
and add it to the result.
4. Return the result.

Please walk through the example below for more understanding.


6. Prefix to infix

Algorithm:
Iterate the given expression from right to left (in reverse order), one character at a time

1. If character is operand, push it to stack.


2. If character is operator,
1. pop operand from stack, say it’s s1.
2. pop operand from stack, say it’s s2.
3. perform (s1 operator s2) and push it to stack.
3. Once the expression iteration is completed, initialize result string and pop out from stack and add it
to result.
4. Return the result.

Please walk through the example below for more understanding.


QUEUE

A queue is linear data structure and collection of elements. A queue is another special kind of
list, where items are inserted at one end called the rear and deleted at the other end called the
front. The principle of queue is a “FIFO” or “First-in-first-out”.
Queue is an abstract data structure. A queue is a useful data structure in programming. It is
similar to the ticket queue outside a cinema hall, where the first person entering the queue
is the first person who gets the ticket.
A real-world example of queue can be a single-lane one-way road, where the vehicle enters
first, exits first.

More real-world examples can be seen as queues at the ticket windows and bus-stops and our
college library.

The operations for a queue are analogues to those for a stack; the difference is that the
insertions go at the end of the list, rather than the beginning.

Applications of Queue
1. Queues are widely used as waiting lists for a single shared resource like printer, disk, CPU.
2. Queues are used in asynchronous transfer of data (where data is not being transferred at the same
rate between two processes) for eg. pipes, file IO, sockets.
3. Queues are used as buffers in most of the applications like MP3 media player, CD player, etc.
4. Queue are used to maintain the play list in media players in order to add and remove the songs from
the play-list.
5. Queues are used in operating systems for handling interrupts.

Basic Operations of Queue

A queue is an object (an abstract data structure - ADT) that allows the following operations:

 Enqueue(insertion): Add an element to the end of the queue


 Dequeue(Deletion): Remove an element from the front of the queue
 IsEmpty: Check if the queue is empty
 IsFull: Check if the queue is full
 Peek: Get the value of the front of the queue without removing it

Working of Queue

Queue operations work as follows:

 two pointers FRONT and REAR


 FRONT track the first element of the queue
 REAR track the last element of the queue
 initially, set value of FRONT and REAR to -1

Enqueue Operation

 check if the queue is full

 for the first element, set the value of FRONT to 0


 increase the REAR index by 1
 add the new element in the position pointed to by REAR
Dequeue Operation
 check if the queue is empty

 return the value pointed by FRONT


 increase the FRONT index by 1
 for the last element, reset the values of FRONT and REAR to -1

Representation of Queue (or) Implementation of Queue:


The queue can be represented in two ways:
1. Queue using Array
2. Queue using Linked List

Array representation of Queue

We can easily represent queue by using linear arrays. There are two variables i.e. front and rear, that are
implemented in the case of every queue. Front and rear variables point to the position from where
insertions and deletions are performed in a queue. Initially, the value of front and rear is -1 which
represents an empty queue. Array representation of a queue containing 5 elements along with the
respective values of front and rear, is shown in the following figure.

The above figure shows the queue of characters forming the English word "HELLO". Since, No
deletion is performed in the queue till now, therefore the value of front remains -1 . However, the
value of rear increases by one every time an insertion is performed in the queue. After inserting an
element into the queue shown in the above figure, the queue will look something like following. The
value of rear will become 5 while the value of front remains same.
After deleting an element, the value of front will increase from -1 to 0. however, the queue will look
something like following.
CIRCULAR QUEUE

A circular queue is the extended version of a queue where the last element is connected to the first element.
Thus forming a circle-like structure.

The circular queue solves the major limitation of the normal queue. In a normal queue, after a bit of
insertion and deletion, there will be non-usable empty space.

Here, indexes 0 and 1 can only be used after resetting the queue (deletion of all elements).
This reduces the actual size of the queue.
Circular Queue Operations

The circular queue work as follows:

 two pointers FRONT and REAR


 FRONT track the first element of the queue
 REAR track the last elements of the queue
 initially, set value of FRONT and REAR to -1

1. Enqueue(Insertion) Operation

 check if the queue is full

 for the first element, set value of FRONT to 0


 circularly increase the REAR index by 1 (i.e. if the rear reaches the end, next it would be at the start of the
queue)
 add the new element in the position pointed to by REAR
2. Delete Operation

 check if the queue is empty

 return the value pointed by FRONT


 circularly increase the FRONT index by 1
 for the last element, reset the values of FRONT and REAR to -1

However, the check for full queue has a new additional case:

 Case 1: FRONT = 0 && REAR == SIZE - 1


 Case 2: FRONT = REAR + 1
The second case happens when REAR starts from 0 due to circular increment and when its value is just 1
less than FRONT, the queue is full.
1. Difference between stacks and Queues?
stacks Queues
1. A stack is a linear list of elements in 1. A Queue is a linerar list of elements in
which the element may be inserted or which the elements are added at one end and
deleted at one end. deletes the elements at another end.
2. . In Queue the element which is inserted
2. In stacks, elements which are inserted first is the element deleted first.
last is the first element to be deleted.
3. Queues are called FIFO (First In
3. Stacks are called LIFO (Last In First Out)list.
First Out)list
4. In Queue elements are removed in the
4. In stack elements are removed in reverse same order in which thy are inserted.
order in which thy are inserted.
5. Suppose the elements a,b,c,d,e are inserted
5. suppose the elements a,b,c,d,e are in the Queue, the deletion of elements will be
inserted in the stack, the deletion of in the same order in which thy are inserted.
elements will be e,d,c,b,a.
6. In Queue there are two pointers one for
6. In stack there is only one pointer to insert insertion called “Rear” and another for
and delete called “Top”. deletion called “Front”.

7. Initially top=-1 indicates a stack is empty. 7. Initially Rear=Front=-1 indicates a Queue


is empty.
8. Stack is full represented by the condition
TOP=MAX-1(if array index starts from 8. Queue is full represented by the condition
‘0’). Rear=Max-1.

9. To push an element into a stack, Top is 9. To insert an element into Queue, Rear is
incremented by one incremented by one.

10. To POP an element from stack,top 10. To delete an element from Queue, Front is
is decremented by one.
incremented by one.
11.The conceptual view of Stack is as
follows: 11.The conceptual view of Queue is as
follows:

You might also like