0% found this document useful (0 votes)
15 views21 pages

DS Module2

A stack is an Abstract Data Type (ADT) that operates in a Last-in-first-out (LIFO) manner, allowing insertion and deletion at one end called the top. Basic operations include Push (insertion), Pop (deletion), and Display, with applications in expression evaluation and conversion. A queue, on the other hand, is a linear data structure that follows a First-in-first-out (FIFO) principle, with operations for insertion, deletion, and display, commonly used in task scheduling and resource management.

Uploaded by

f35503056
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)
15 views21 pages

DS Module2

A stack is an Abstract Data Type (ADT) that operates in a Last-in-first-out (LIFO) manner, allowing insertion and deletion at one end called the top. Basic operations include Push (insertion), Pop (deletion), and Display, with applications in expression evaluation and conversion. A queue, on the other hand, is a linear data structure that follows a First-in-first-out (FIFO) principle, with operations for insertion, deletion, and display, commonly used in task scheduling and resource management.

Uploaded by

f35503056
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

STACK

A stack is an Abstract Data Type (ADT), commonly used in most programming languages. It is a
linear data structure which operates in Last-in-first-out (LIFO) fashion. In this case the element
which is inserted at first is deleted first. It is named stack as it behaves like a real-world stack,
for example – a deck of cards or a pile of plates, etc.

A real-world stack allows operations at one end only. For example, we can place or remove a
card or plate from the top of the stack only. Likewise, Stack ADT allows all data operations at
one end only called top of stack (TOP). At any given time, we can only access the top element of
a stack.
This feature makes it LIFO data structure. LIFO stands for Last-in-first-out. Here, the element
which is placed (inserted or added) last is accessed first. In stack terminology, insertion operation
is called PUSH operation and removal operation is called POP operation.

Stack Representation
The following diagram depicts a stack and its operations –

A stack can be implemented by means of Array, Structure, Pointer, and Linked List. Stack can
either be a fixed size one or it may have a sense of dynamic resizing.
Basic Operations

The fundamental operations which are possible on a stack are:

Push(): -> Insertion of element on the stack.


Pop():-> Deletion of element from the stack
Peep():-> Extraction of element from the stack
Update():-> Update the information associated at some location in the stack.

Algorithm for Push operation

The process of putting a new data element onto stack is known as a Push Operation. Steps
required inserting element onto stack.
Step 1 − Checks if the stack is full.
Step 2 − If the stack is full, display overflow message and exit.
Step 3 − If the stack is not full, then increase the value of top by 1 to point next empty space.
Step 4 − Adds data element to the stack location, where top is pointing.
Step 5 − Returns success.

Procedure Push(Stack, value, top, n)

/*This procedure Push is used to add a new element which is stored in

‘value’ variable into a stack of size n. top variable is used to show top of

the stack element. */

If (top<n-1)
{

top=top+1;

Stack[top]=value;

else

print (“ Stack Overflow”);

Algorithm for Pop operation

The process of removing (deleting) data element from stack is known as a Pop Operation. Steps
required for Pop operation.

Step 1 − Checks if the stack is empty or underflow.


Step 2 − If the stack is empty, display underflow message and exit.
Step 3 − If the stack is not empty, accesses the data element at which top is pointing.
Step 4 − Decreases the value of top by 1.
Step 5 − Returns success.
Procedure Pop(Stack, value, top, n)

/* This procedure Pop is used to remove an element which is stored in

‘value’ variable from a stack of size n. top variable is used to show top

of the stack element. */

If (top>=0)

value= Stack[top];

top=top-1;

else

print (“ Stack Underflow”);

}
print value;

Algorithm for Display operation

The process of showing data element from stack is known as a Display Operation. Steps required
for Display operation.

Step 1 − Checks if the stack is empty or underflow.


Step 2 − If the stack is empty, display underflow message and exit.
Step 3 − If the stack is not empty, accesses the data element from lower index value (i.e 0) to
top location by using loop.
Step 4 − stop.
Procedure Display(Stack, top, n)

/* This procedure Display is used to show elements of stack of size n. top

variable is used to show top of the stack element. */

local variable i;

If (top>=0)

for ( i=0; i<=top; i=i+1)

print(Stack[i]);

else

print (“ Stack Underflow”);

}
Both Push and Pop operations will take constant O(1) time if we implement stack through
array.

Applications of Stacks
Following are the applications of stack:

1. Expression Evaluation
2. Expression Conversion
i. Infix to Postfix
ii. Infix to Prefix
iii. Postfix to Infix
iv. Prefix to Infix
3. Backtracking Problem

4. Memory Management
Expression Evaluation

Stack data structure is used for evaluating the given expression. For example, consider the
following expression
15 * (6 + 2) - 8 / 4
Since parenthesis has the highest precedence among the arithmetic operators, (6 +2) = 8 will be
evaluated first. Now, the expression becomes
15 * 8 - 8 / 4
* and / have equal precedence and their associativity is from left-to-right. So, start evaluating the
expression from left-to-right.
15 * 8 = 120 and 8 / 4 =2
Now, the expression becomes 120 – 2 and the value returned after the subtraction operation
is 118.

Expression Representation

There are three popular methods used for representation of an expression and it is also called
Polish Notation.

Infix A+B Operator between operands.


Prefix + AB Operator before operands.
Postfix AB + Operator after operands.

1. Conversion of Infix to Postfix

Algorithm for Infix to Postfix

Step 1: Consider the next element in the input.

Step 2: If it is operand, display it.

Step 3: If it is opening parenthesis, insert it on stack.

Step 4: If it is an operator, then

 If stack is empty, insert operator on stack.


 If the top of stack is opening parenthesis, insert the operator on stack
 If it has higher priority than the top of stack, insert the operator on stack.
 Else, delete the operator from the stack and display it, repeat Step 4.

Step 5: If it is a closing parenthesis, delete the operator from stack and display them until an

opening parenthesis is encountered. Delete and discard the opening parenthesis.

Step 6: If there is more input, go to Step 1.

Step 7: If there is no more input, delete the remaining operators to output.

Example: Suppose we are converting 3*3/(4-1)+6*2 expression into postfix form.

Following table shows the evaluation of Infix to Postfix:

Expression Stack Output


3 Empty 3
* * 3
3 * 3,3
/ / 3,3,*
( /( 3,3,*
4 /( 3,3,*,4
- /(- 3,3,*,4
1 /(- 3,3,*,4,1
) - 3,3,*,4,1,-
+ + 3,3,*,4,1,-/
6 + 3,3,*,4,1,-,/6
* +* 3,3,*,4,1,-,/6,2
2 +* 3,3,*,4,1,-,/6,2
Empty 3,3,*,4,1,-,/6,2,*,+

So, the Postfix Expression is 3,3,*,4,1,-,/,6,2,*,+

2. Infix to Prefix

Algorithm for Infix to Prefix Conversion:

Step 1: Insert “)” onto stack, and add “(” to end of the A .
Step 2: Scan A from right to left and repeat Step 3 to 6 for each element of A until the stack is
empty.

Step 3: If an operand is encountered, add it to B .

Step 4: If a right parenthesis is encountered, insert it onto stack .

Step 5: If an operator is encountered then,


a. Delete from stack and add to B (each operator on the top of stack) which has same or
higher precedence than the operator.
b. Add operator to stack.

Step 6: If left parenthesis is encountered then ,


a. Delete from the stack and add to B (each operator on top of stack until a left
parenthesis is encountered).
b. Remove the left parenthesis.

Step 7: Exit

3. Postfix to Infix

Following is an algorithm for Postfix to Infix conversion:

Step 1: While there are input symbol left.

Step 2: Read the next symbol from input.

Step 3: If the symbol is an operand, insert it onto the stack.

Step 4: Otherwise, the symbol is an operator.

Step 5: If there are fewer than 2 values on the stack, show error /* input not sufficient values in
the expression */

Step 6: Else,
a. Delete the top 2 values from the stack.
b. Put the operator, with the values as arguments and form a string.
c. Encapsulate the resulted string with parenthesis.
d. Insert the resulted string back to stack.

Step 7: If there is only one value in the stack, that value in the stack is the desired infix string.

Step 8: If there are more values in the stack, show error /* The user input has too many values */
4. Prefix to Infix

Algorithm for Prefix to Infix Conversion

Step 1: The reversed input string is inserted into a stack -> prefixToInfix(stack)

Step 2: If stack is not empty,


a. Temp -> pop the stack
b. If temp is an operator,
Write a opening parenthesis “(“ to show -> prefixToInfix(stack)
Write temp to show -> prefixToInfix(stack)
Write a closing parenthesis “)” to show
c. Else If temp is a space ->prefixToInfix(stack)
d. Else, write temp to show if [Link] != space ->prefixToInfix(stack)

Example: Suppose we are converting /-bc+-pqr expression from Prefix to Infix.

Following table shows the evaluation of Prefix to Infix Conversion:

Expression Stack

-bc+-pqr Empty

/-bc+-pq “q”
“r”

/-bc+- “p”
“q”
“r”

/-bc+ “p-q”
“r”

/-bc “p-q+r”

/-b “c”
“p-q+r”

/- “b”
“c”
“p-q+r”

/ “b-c”
“p-q+r”

NULL “((b-c)/((p-q)+r))”

So, the Infix Expression is ((b-c)/((p-q)+r))


QUEUE
A queue is a linear data structure in which insertion of an element can take place only at one end
called the rear and deletion can take place on the other end which is termed as the front. In the
concept of a queue, the first element to be inserted in the queue will be the first element to be
deleted or removed from the queue (list). So Queue is said to follow the FIFO (First In First Out)
structure or FCFS (First Come First Serve). A real-life example for queue will be the queue of
people waiting to accomplish a particular task where the first person in the queue is the first
person to be served first.
Other examples can also be noted within a computer system where the queue of tasks arranged in
the list to perform for the line printer, for accessing the disk storage, or even in the time-sharing
system for the use of CPU. So basically queue is used within a single program where there are
multiple programs kept in the queue or one task may create other tasks which must have to be
executed in turn by keeping them in the queue.
The below diagrams tries to explain queue representation as data structure
Types of Queue

1. Simple Queue
2. Circular Queue
3. Priority Queue
4. Dequeue (Double Ended Queue)

Simple Queue

The simple queue is a normal queue where insertion takes place at the FRONT of the queue and
deletion takes place at the END of the queue.

Circular Queue

Unlike the simple queues, in a circular queue each node is connected to the next node in
sequence but the last node’s pointer is also connected to the first node’s address. Hence, the last
node and the first node also gets connected making a circular link overall. Circular queue is also
called as Ring Buffer.

Priority Queue

A priority queue is a collection of elements such that each element has been assigned a priority
and such that the order in which the elements are deleted and processed comes from the
following rules

a) An element of higher priority is processed before any elements with the lower priority.

b) Two elements with the same priority are processed according to the order in which they were
added to the queue.

Dequeue (Doubly Ended Queue)

In a Double Ended Queue, insertion and deletion operations can be done at


both FRONT and REAR end of the queue.
Basic Operation performed on Queue

Insert( ) − add (store) an item to the queue.

Delete( ) − remove (access) an item from the queue.

Display( )- viewing the entire elements of queue.

Operations on simple queue

Inserting element into a queue


The following steps should be taken to insert data into a queue –

Step 1 − Check if the queue is full.


Step 2 − If the queue is full, produce overflow error and exit.
Step 3 − If the queue is not full, increment rear by 1 i.e. pointer to point the next empty space.
Step 4 − Add data element to the queue location, where the rear is pointing.
Step 5 − return success.
Algorithm for inserting element into queue

Procedure insert_queue( queue[ ], n , rear, front )

/* This procedure is used to add (insert) element into a queue of size n.


rear and front is two ends of queue */

Local variable item;

if (front=-1 and rear=-1)

front=0;

rear=0;

queue[rear]=item;

else if (rear<n-1 and front<=rear)

rear=rear+1;

queue[rear]=item;

else

print “Queue overflow”;

}
Deleting element from a Queue
The following steps should be taken to insert data into a queue –

Step 1 − Check if the queue is empty.


Step 2 − If the queue is empty, produce underflow error and exit.
Step 3 − If the queue is not empty, access the data where front is pointing.
Step 4 − Increment front pointer to point to the next available data element.
Step 5 − Return success.

Algorithm for deleting element from queue

Procedure delete_queue( queue[ ], n , rear, front )

/* This procedure is used to remove (delete) element into a queue of size


n. rear and front is two ends of queue */

Local variable item;

if (front=-1 or front>rear)

print “Queue underflow”;

exit;

}
else if (front=0)

item=queue[front];

front=-1;

rear=-1;

else

item=queue[front];

front=front+1;

}
print item;

Algorithm for displaying elements from a queue

Procedure display_queue( queue[ ], n , rear, front )

/* This procedure is used to show elements of a queue of size


n. rear and front is two ends of queue */

Local variable i;

if (front=-1 or front>rear)

print “Queue underflow”;

exit;
}

else

for(i=front; i<=rear; i=i+1)

print queue[i];

Applications of Queue
As the name suggests is used whenever we need to manage any group of task in an order in
which the first one coming in, also gets out first while the others wait for their turn, like in the
following scenarios:

1. Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
2. In real life scenario, railway reservation counter, people uses Queue to book tickets.
3. Handling of interrupts in real-time systems. The interrupts are handled in the same order
as they arrived i.e First come first served.

Complexity Analysis of Queue Operations


Just like Stack, in case of a Queue too, we know exactly, on which position new element will be
added and from where an element will be removed, hence both these operations requires a single
step.

 Insertion: O(1)
 Deletion: O(1)

Algorithm to insert element into a circular queue

Procedure insert_CQ( queue[ ], n , rear, front )


{

/* This procedure is used to add (insert) element into a circular queue of


size n. rear and front is two ends of circular queue */

local variable item;

if (front=0 and rear=n-1)

print “Overflow”;

return;

else if (front=-1)

front=0;

rear=0;

queue[rear]=item;

else if (rear=n-1)

rear=0;

queue[rear]=item;

else

rear=rear+1;

queue[rear]=item;

Algorithm to delete element from a circular queue

Procedure delete_CQ( queue[ ], n , rear, front )


{

/* This procedure is used to delete element into a circular queue of size n. rear
and front is two ends of circular queue */

local variable item;

if (front=-1)

print “Underflow”;

return;

item=queue[front];

if (front=-rear+1)

front=-1;

rear=-1;

else if (front=n-1)

front=0;

else

front=front+1;

print item;

Algorithm to delete element from a circular queue

Procedure display_CQ( queue[ ], n , rear, front )


{

/* This procedure is used to show elements of a circular queue of size n. rear

and front is two ends of circular queue */

local variable i;

if (front=-1)

print “Underflow”;

return;

else if (front<=rear)

for( i=front; i<=rear; i=i+1)

print (queue[i]);

else

for(i=0; i<=rear; i=i+1)

print (queue[i]);

for(i=front; i<=n-1; i=i+1)

print (queue[i]);

}
}

You might also like