UNIT 2 FINAL

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

STACK ADT:-

 A Stack is a linear data structure where insertion and deletion of items takes place at one end
called top of the stack.
 A Stack is defined as a data structure which operates on a last-in first-out basis. So it is also is
referred as Last-in First-out( LIFO).
 Stack uses a single index or pointer to keep track of the information in the stack.
 A stack pointer keeps track of the current position on the stack.
 When an element is placed on the stack, it is said to be pushed on the stack.
 When an object is removed from the stack, it is said to be popped off the stack.
 stack overflow-> which occurs when we try to push more information on a stack that it can
hold
 stack underflow -> which occurs when we try to pop an item off a stack which is empty.
The basic operations associated with the stack are:
a) push(insert) an item onto the stack.
b) pop(remove) an item from the stack
Pushing items onto the stack
 The array elements begin at 0 ( because the array subscript starts from 0)
 The maximum elements that can be placed in stack is max.
 The stack pointer, top, is considered to be pointing to the top element of the stack.
 A push operation thus involves adjusting the stack pointer to point to next free slot and then
copying data into that slot of the stack.
 Initially the top is initialized to -1.
Routine to Push an element into the stack using Array

void push(int ele)


{
if(top==max-1)
cout<<"Stack Overflow...\n";
else
{
top++;
stack[top]=ele;
cout<<"Pushed Sucesfully....\n";
}
}

Popping an element from stack:

 To remove an item, first extract the data from top position in the stack and
 then decrement the stack pointer, top.
Routine to Pop an element from the stack using Array
Void pop()
{
If(top==-1)
{
Cout<<“Stack is Underflow”;
}
else
{
Cout<<“Delete data :”stack[top]; top=top-1;
}}
Display the elements in the Stack
void display()
{
If(top==-1)
{
Cout<<“Stack is Underflow”;
}
else
{
Cout<<“Display elements are:;
for(i=top;i>=0;i--)
Cout<<stack[i];
}
}
Stack using Linked List:

LINKED LIST IMPLEMENTATION OF STACK


Routine to push an element into the stack:
void push(int ele)
{
Node *temp=new Node();
temp->data=ele;
temp->next=NULL;
if(top==NULL)
top=temp;
else
{
temp->next=top;
top=temp;
}
cout<<endl<<"Element is Pushed Successfully";
}
Routine to pop an element from the stack:
void pop()
{
if(top==NULL)
cout<<endl<<"stack is empty";
else
{
temp=top;
top=top->next;
cout<<"Element "<<temp->data<<" is removed from list";
delete(temp);
}
}
Routine to display an element from the stack:
void display()
{
cout<<endl<<"Linked List \n";
list=top;
while(list!=NULL)
{
cout<<”Top<<list->data<<"-->";
list=list->next;
}
cout<<"NULL";
}

Applications of stack:
 Stack is used to convert an infix expression into postfix/prefix form.
 Stack is used by compilers to check for balancing of parentheses, brackets and braces.
 Stack is used to evaluate a postfix expression.
 In recursion, all intermediate arguments and return values are stored on the processor’s stack.
 During a function call the return address and arguments are pushed onto a stack and on return
they are popped off.
Conversion from infix to postfix:
Procedure to convert from infix expression to postfix expression is as follows:
 Scan the infix expression from left to right.
a) If the scanned symbol is left parenthesis, push it onto the stack.
b)If the scanned symbol is an operand, then place directly in the postfix expression (output).
c)If the symbol scanned is a right parenthesis, then go on popping all the items from the stack
and place them in the postfix expression till we get the matching left parenthesis.
d)If the 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 greater than or equal) to the precedence of the
scanned operator and push the scanned operator onto the stack otherwise, push the scanned
operator onto the stack.
Precedence
Example 1

Postfix notation:

The general mathematical way of representing algebraic expressions is to write the operator
between operands: Example: a + b. Such representation is called the Infix representation. If
we write the operator after the operands Example: a b +, it is called the Postfix
representation. It is also called the "Reverse Polish notation".

Evaluation of Postfix expression

Steps:

 Start a scanning process from left to right and one symbol at a time
 If the symbol is operand, then push onto the stack
 If the symbol is an operator, pop the stack twice to obtain two operands and perform
operations by using the operator
 Push the outcome of operation
 This process to be continued until the end of the input string.
 Remove the final value from the stack

Tower of Hanoi
The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods(A, B,
and C), and a number of disks of different sizes.Initially, all the disks are stacked in
decreasing value of diameter i.e., the smallest disk is placed on the top and they are on
rod A. The puzzle starts with the disks in a neat stack in order of size on one rod, the
smallest at the top, thus making a conical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying the
following simple rules:
1. Only one disk can be moved at a time.
2. Each move consists of taking the upper disk from one of the stacks and placing it on
top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.

3. No disk may be placed on top of a smaller disk.


Follow the steps below to solve the problem:
 Create a function towerOfHanoi where pass the N (current number of disk), from_rod,
to_rod, aux_rod.
 Make a function call for N – 1 th disk.
 Then print the current the disk along with from_rod and to_rod
 Again make a function call for N – 1 th disk.

Routine :
void towerOfHanoi(int n, char from_rod, char to_rod,
char aux_rod)
{
if (n == 0) {
return;
}
towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);
cout << "Move disk " << n << " from rod " << from_rod
<< " to rod " << to_rod << endl;
towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);
}

QUEUE ADT:
A queue is an abstract data structure that contains a collection of elements. Queue
implements the FIFO mechanism i.e., the element that is inserted first is also deleted
first. In other words, the least recently added element is removed first in a queue.
Basic Operations on Queue:
•enqueue(): Inserts an element at the end of the queue i.e. at the rear end.

•dequeue(): This operation removes and returns an element that is at the front end of
the queue.

•front(): This operation returns the element at the front end without removing it.

•rear(): This operation returns the element at the rear end without removing it.

•isEmpty(): This operation indicates whether the queue is empty or not.

•isFull(): This operation indicates whether the queue is full or not.

•size(): This operation returns the size of the queue i.e. the total number of elements it
contains.

Types of Queues

•Simple Queue:
• Simple queue also known as a linear queue is the most basic version of a queue.
• Insertion of an element i.e. the Enqueue operation takes place at the rear end
• Removal of an element i.e. the Dequeue operation takes place at the front end.

•Circular Queue:
•The element of the queue act as a circular ring.
•The working of a circular queue is similar to the linear queue except for the fact that the last
element is connected to the first element. Its advantage is that the memory is utilized in a
better way. This is because if there is an empty space i.e. if no element is present at a certain
position in the queue, then an element can be easily added at that position using modulo
capacity(%n).

•Priority Queue: This queue is a special type of queue. Its specialty is that it arranges the
elements in a queue based on some priority. The priority can be something where the element
with the highest value has the priority so it creates a queue with decreasing order of values.
The priority can also be such that the element with the lowest value gets the highest priority
so in turn it creates a queue with increasing order of values. In pre-define priority queue, C++
gives priority to highest value whereas Java gives
Some of the Application of Queue in Data Structure
Here are some of the common application of queue in data structure:

 Queues can be used to schedule jobs and ensure that they are executed in
the correct order.
 Queues can be used to manage the order in which print jobs are sent to the
printer.
 Queues are used to implement the breadth-first search algorithm.
 Queues can be used to manage incoming calls and ensure that they are
handled in the correct order.
 Queues can be used to manage the order in which processes are executed
on the CPU.
 Queues can be used for buffering data while it is being transferred between
two systems. When data is received, it is added to the back of the queue,
and when data is sent, it is removed from the front of the queue.
Other Application of Queue in Data Structure
Some other application of queue in data structure:

 Applied as buffers on playing music in the mp3 players or CD players.


 Applied on handling the interruption in the operating system.
 Applied to add a song at the end of the playlist.
 Applied as the waiting queue for using the single shared resources like
CPU, Printers, or Disk.
 Applied to the chat application when someone sends messages to us and
we don’t have an internet connection then the messages are stored in the
server of the chat application
Implementation of Queue
Two ways queue can be implemented
• Using Array
• Using Linked List

Implementation of Queue using Array

Steps for enqueue:


1.Check the queue is full or not
2.If full, print overflow and exit
3.If queue is not full, increment tail and add the element

Routine for Enqueue


void enqueue(int ele)
{
if (rear == max_size - 1)
cout<<"Queue Overflow"<<endl;
else
{
if (front == - 1)
front = 0;
rear++;
queue[rear] = ele;
}
}

Steps for dequeue:


1.Check queue is empty or not
2.if empty, print underflow and exit
3.if not empty, print element at the head and increment head

Routine for Dequeue

void Dequeue()
{
if (front == - 1 || front > rear)
Routine
cout<<"Queue Underflow ";
for Display
else
{
cout<<"Element deleted from queue is : "<< queue[front] <<endl;
void front++;;
Display() }
{
if (front == - 1)
cout<<"Queue is empty"<<endl;
else
{
cout<<"Queue elements are : ";
for (int i = front; i <= rear; i++)
cout<<queue[i]<<" ";
}
}

CIRCULAR QUEUE
• In Circular Queue, the insertion of a new element is performed at the very first location of the queue
if the last location of the queue is full, in which the first element comes just after the last element.

Advantages

• It overcomes the problem of unutilized space in linear queues, when it is implemented as arrays.

To perform the insertion of an element to the queue, the position of the element is calculated by the
relation as Rear = (Rear + 1) % Maxsize.
and then set
Queue [Rear] = value.

Routine to insert an element in circular queue

void CEnqueue (int ele)


{
if (Front = = (rear + 1) % Maxsize)
Cout<<“Queue is overflow”;
else
{
if (front = = -1)
front = rear = 0;
else
{
rear = (rear + 1)% Maxsize;
CQueue [rear] = ele;
}
}
}

Routine to delete an element from circular queue


To perform the deletion, the position of the Front printer is calculated by the relation

Value = CQueue [Front]


Front = (Front + 1) % maxsize.

Routine to delete an element from circular queue


int CDequeue ( )
{
if (front = = -1)
cout<<“Queue is underflow”;
else
{
value = CQueue [Front]
front = (Front + 1) % maxsize.
free(value)
}

DOUBLE ENDED QUEUE (DEQUE)


• In Double Ended Queue, insertion and deletion operations are performed at both the ends.

Deque

APPLICATIONS OF QUEUE
 Batch processing in an operating system
 To implement Priority Queues.
 Priority Queues can be used to sort the elements using Heap Sort.
 Simulation.
 Mathematics user Queueing theory.
 Computer netQworks where the server takes the jobs of the client as per the queue strategy.
Steps to Implement Queue using Linked List in C++

 We will create a Linked list to perform the operations on the queue.


 Create a linked list to insert the elements .
 Similarly, Perform the deletion operation in Linked List.
 Implement all the methods of the queue in a Linked List.

The Linked List Implementation of queue is also better in terms of

 space
 memory
 time complexity
void enqueue (Node ** head, int data)
{

Node *new_node = new Node ();

// assign data value


new_node->data = data;
// change the next node of this new_node
// to current head of Linked List
new_node->next = *head;

//changing the new head to this newly entered node


*head = new_node;

void dequeue (Node ** head)


{
Node *temp = *head;

// if there are no nodes in Linked List can't delete


if (*head == NULL)
{
cout << ("Linked List Empty, nothing to delete");
return;
}
void display (Node * node)
{

//as linked list will end when Node is Null


while (node != NULL)
{
cout << node->data << " ";
node = node->next;
}
cout << endl;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy