Stacks have several application areas including:
1) When functions are called to save return addresses and local variables.
2) To convert infix expressions to postfix form by acting as a placeholder.
3) To evaluate postfix expressions by holding operands and intermediate results.
In computer science, a stack is an abstract data type that serves as a collection of elements, with two main principal operations: push, which adds an element to the collection, and pop, which removes the most recently added element that was not yet removed.
Prefix and PostFIx presentation for DSA .pptxrtiwary190801
In prefix notation (Polish notation), operators precede their operands, making the expression evaluation unambiguous and eliminating the need for parentheses. For example, the prefix expression `+ 3 4` corresponds to the infix expression `3 + 4`.
In postfix notation (Reverse Polish notation), operators follow their operands, allowing for efficient computation using a stack and similarly eliminating parentheses. For example, the postfix expression `3 4 +` corresponds to the infix expression `3 + 4`.
The document discusses stacks and queues, which are fundamental data structures that can insert and remove items. Stacks follow the LIFO (last in, first out) principle, while queues follow the FIFO (first in, first out) principle. The document provides implementations of stacks and queues using linked lists and arrays and examples of their applications in parsing, compilers, undo functions, and more.
The document discusses stacks and their implementation and use. It begins by defining a stack as a collection of items that can be inserted or deleted from one end, following the LIFO principle. Common stack operations like push, pop and top are introduced. Stacks can be implemented using arrays or linked lists. The use of stacks to evaluate expressions in prefix, infix and postfix notations is covered, including the precedence of operators and the process to convert infix to postfix notation using a stack. Parentheses are also discussed in the conversion process.
The document discusses stacks and converting expressions between infix, postfix, and prefix notation. It provides examples and algorithms for converting infix expressions to postfix. The algorithms involve using an operator stack to determine the order of operations based on precedence rules. Operands are added to the output string and operators are pushed to the stack or popped and added to the output string based on their precedence.
This document discusses applications of stacks, including converting between infix, prefix, and postfix notation. It provides examples of evaluating arithmetic expressions in postfix notation. Key points include:
- Prefix notation places the operator before operands, postfix places after, and infix between.
- Converting infix to prefix moves operators left and removes parentheses. Converting to postfix moves operators to output list in order of evaluation.
- Postfix notation avoids needing parentheses and is evaluated by pushing operands, popping to apply operators, and pushing results back onto the stack.
Infix to Postfix Conversion Using StackSoumen Santra
Infix to Postfix Conversion Using Stack is one of the most significant example of application of Stack which is an ADT (Abstract Data Type) based on LIFO concept.
The document discusses stacks and their applications. It defines a stack as a Last In First Out (LIFO) data structure. Key stack operations are described such as push, pop, and peek. An array implementation of a stack is presented and applications like checking balanced brackets, converting infix to postfix notation, and postfix calculators are covered. Example code and diagrams are provided to illustrate stack concepts and operations.
The document discusses stacks, which are linear data structures that follow the LIFO (last in, first out) principle. Stacks can be implemented using arrays or linked lists. Elements are inserted and removed only from one end, called the top of the stack. Insertion is called pushing and removal is called popping. Stacks are used extensively in computer systems, for example in operating system function calls and interrupt handling. The Java programming language contains a Stack class that can be used by programmers.
The document provides an outline for a lecture on applications of stacks and queues, including syntax parsing, expression evaluation, backtracking, and printing jobs. It discusses infix, postfix, and prefix notation and how to convert between them using stacks. It also explains how to check parentheses in an expression and evaluate postfix expressions using stacks and queues.
The document discusses converting infix expressions to postfix expressions using a stack. It defines infix and postfix expressions, provides examples of each, and presents an algorithm that uses a stack to scan an infix expression from left to right and output an equivalent postfix expression. Key steps include pushing operators to the stack based on precedence and popping operators to the output when encountering operands and parentheses.
The document discusses stacks and their implementation and applications. It describes stacks as linear data structures that follow the LIFO principle, and how they can be implemented using arrays. Key stack operations like push and pop are explained along with the concepts of overflow and underflow. Applications of stacks include evaluating postfix expressions, converting infix to postfix notation, and recursion. Algorithms for infix to postfix conversion and evaluating postfix expressions are provided with examples.
This document discusses stack applications and operations. It provides examples of how stacks can be used for reversing data, converting decimal to binary, evaluating arithmetic expressions by converting infix to postfix notation, and backtracking. Basic stack operations include push, pop, and peeking at the top element. Stacks follow LIFO order and are commonly implemented using arrays or linked lists. Common applications include reversing strings or files, evaluating arithmetic expressions, and backtracking to achieve goals.
Please need help on C++ language.Infix to Postfix) Write a program.pdfpristiegee
Please need help on C++ language.
Infix to Postfix) Write a program that converts an infix expression into an equivalent postfix
expression. The rules to convert an infix expression into an equivalent postfix expression are as
follows:
Initialize pfx to an empty expression and also initialize the stack.
Get the next symbol, sym, from infx.
If sym is an operand, append sym to pfx.
If sym is (, push sym into the stack.
If sym is ), pop and append all of the symbols from the stack until the most recent left
parentheses. Pop and discard the left parentheses.
If sym is an operator:
Pop and append all of the operators from the stack to pfx that are above the most recent left
parentheses and have precedence greater than or equal to sym.
Push sym onto the stack.
After processing infx, some operators might be left in the stack. Pop and append to pfx
everything from the stack.
In this program, you will consider the following (binary) arithmetic operators: +, -, *, and /.
You may assume that the expressions you will process are error free. Design a class that stores
the infix and postfix strings. The class must include the following operations:
getInfix: Stores the infix expression.
showInfix: Outputs the infix expression.
showPostfix: Outputs the postfix expression.
convertToPostfix: Converts the infix expression into a postfix expression. The resulting postfix
expression is stored in pfx.
precedence: Determines the precedence between two operators. If the first operator is of higher
or equal precedence than the second operator, it returns the value true; otherwise, it returns the
value false.
A + B - C;
(A + B ) * C;
(A + B) * (C - D);
A + ((B + C) * (E - F) - G) / (H - I);
A + B * (C + D ) - E / F * G + H;
Infix Expression: A+B-C;
Postfix Expression: AB+C-
Infix Expression: (A+B)*C;
Postfix Expression: AB+C*
Infix Expression: (A+B)*(C-D);
Postfix Expression: AB+CD-*
Infix Expression: A+((B+C)*(E-F)-G)/(H-I);
Postfix Expression: ABC+EF-*G-HI-/+
Infix Expression: A+B*(C+D)-E/F*G+H;
Postfix Expression: ABCD+*+EF/G*-H+
PLEASE PROVIDE FOLLOWING.
A UML diagram for your class.
The header file for your class.
The implementation file for your class.
The source code for your test program.
Solution
#include
using namespace std;
const int MAX = 50 ;
class InfixToPostfix
{
private :
char target[MAX], stack[MAX] ;
char *s, *t ;
int top ;
public :
InfixToPostfix( ) ;
void getInfix ( char *str ) ;
void showInfix () ;
void push ( char c ) ;
char pop( ) ;
void convertToPostfix( ) ;
int precedence ( char c ) ;
void showPostfix( ) ;
void Delete();
} ;
InfixToPostfix :: InfixToPostfix( )
{
top = -1 ;
strcpy ( target, \"\" ) ;
strcpy ( stack, \"\" ) ;
t = target ;
s = \"\" ;
}
void InfixToPostfix :: getInfix ( char *str )
{
s = str ;
}
void InfixToPostfix :: showInfix ( )
{
cout<<\"Infix Expression :\"<= precedence ( *s ) )
{
*t = opr ;
t++ ;
opr = pop( ) ;
}
push ( opr ) ;
push ( *s ) ;
}
else
push ( *s ) ;
s++ ;
}
if ( *s == \')\' )
{
opr = pop( ) ;
while ( ( opr ) != \.
A stack is a linear data structure that follows the LIFO (last in, first out) principle. Elements can only be inserted or removed from one end, called the top. Stacks have common operations like push to add an element and pop to remove the top element. Stacks have many applications including evaluating arithmetic expressions in postfix notation, implementing recursion, and solving puzzles like Towers of Hanoi. The document discusses stack implementations using arrays and linked lists and provides examples of stack applications.
Prefix and PostFIx presentation for DSA .pptxrtiwary190801
In prefix notation (Polish notation), operators precede their operands, making the expression evaluation unambiguous and eliminating the need for parentheses. For example, the prefix expression `+ 3 4` corresponds to the infix expression `3 + 4`.
In postfix notation (Reverse Polish notation), operators follow their operands, allowing for efficient computation using a stack and similarly eliminating parentheses. For example, the postfix expression `3 4 +` corresponds to the infix expression `3 + 4`.
The document discusses stacks and queues, which are fundamental data structures that can insert and remove items. Stacks follow the LIFO (last in, first out) principle, while queues follow the FIFO (first in, first out) principle. The document provides implementations of stacks and queues using linked lists and arrays and examples of their applications in parsing, compilers, undo functions, and more.
The document discusses stacks and their implementation and use. It begins by defining a stack as a collection of items that can be inserted or deleted from one end, following the LIFO principle. Common stack operations like push, pop and top are introduced. Stacks can be implemented using arrays or linked lists. The use of stacks to evaluate expressions in prefix, infix and postfix notations is covered, including the precedence of operators and the process to convert infix to postfix notation using a stack. Parentheses are also discussed in the conversion process.
The document discusses stacks and converting expressions between infix, postfix, and prefix notation. It provides examples and algorithms for converting infix expressions to postfix. The algorithms involve using an operator stack to determine the order of operations based on precedence rules. Operands are added to the output string and operators are pushed to the stack or popped and added to the output string based on their precedence.
This document discusses applications of stacks, including converting between infix, prefix, and postfix notation. It provides examples of evaluating arithmetic expressions in postfix notation. Key points include:
- Prefix notation places the operator before operands, postfix places after, and infix between.
- Converting infix to prefix moves operators left and removes parentheses. Converting to postfix moves operators to output list in order of evaluation.
- Postfix notation avoids needing parentheses and is evaluated by pushing operands, popping to apply operators, and pushing results back onto the stack.
Infix to Postfix Conversion Using StackSoumen Santra
Infix to Postfix Conversion Using Stack is one of the most significant example of application of Stack which is an ADT (Abstract Data Type) based on LIFO concept.
The document discusses stacks and their applications. It defines a stack as a Last In First Out (LIFO) data structure. Key stack operations are described such as push, pop, and peek. An array implementation of a stack is presented and applications like checking balanced brackets, converting infix to postfix notation, and postfix calculators are covered. Example code and diagrams are provided to illustrate stack concepts and operations.
The document discusses stacks, which are linear data structures that follow the LIFO (last in, first out) principle. Stacks can be implemented using arrays or linked lists. Elements are inserted and removed only from one end, called the top of the stack. Insertion is called pushing and removal is called popping. Stacks are used extensively in computer systems, for example in operating system function calls and interrupt handling. The Java programming language contains a Stack class that can be used by programmers.
The document provides an outline for a lecture on applications of stacks and queues, including syntax parsing, expression evaluation, backtracking, and printing jobs. It discusses infix, postfix, and prefix notation and how to convert between them using stacks. It also explains how to check parentheses in an expression and evaluate postfix expressions using stacks and queues.
The document discusses converting infix expressions to postfix expressions using a stack. It defines infix and postfix expressions, provides examples of each, and presents an algorithm that uses a stack to scan an infix expression from left to right and output an equivalent postfix expression. Key steps include pushing operators to the stack based on precedence and popping operators to the output when encountering operands and parentheses.
The document discusses stacks and their implementation and applications. It describes stacks as linear data structures that follow the LIFO principle, and how they can be implemented using arrays. Key stack operations like push and pop are explained along with the concepts of overflow and underflow. Applications of stacks include evaluating postfix expressions, converting infix to postfix notation, and recursion. Algorithms for infix to postfix conversion and evaluating postfix expressions are provided with examples.
This document discusses stack applications and operations. It provides examples of how stacks can be used for reversing data, converting decimal to binary, evaluating arithmetic expressions by converting infix to postfix notation, and backtracking. Basic stack operations include push, pop, and peeking at the top element. Stacks follow LIFO order and are commonly implemented using arrays or linked lists. Common applications include reversing strings or files, evaluating arithmetic expressions, and backtracking to achieve goals.
Please need help on C++ language.Infix to Postfix) Write a program.pdfpristiegee
Please need help on C++ language.
Infix to Postfix) Write a program that converts an infix expression into an equivalent postfix
expression. The rules to convert an infix expression into an equivalent postfix expression are as
follows:
Initialize pfx to an empty expression and also initialize the stack.
Get the next symbol, sym, from infx.
If sym is an operand, append sym to pfx.
If sym is (, push sym into the stack.
If sym is ), pop and append all of the symbols from the stack until the most recent left
parentheses. Pop and discard the left parentheses.
If sym is an operator:
Pop and append all of the operators from the stack to pfx that are above the most recent left
parentheses and have precedence greater than or equal to sym.
Push sym onto the stack.
After processing infx, some operators might be left in the stack. Pop and append to pfx
everything from the stack.
In this program, you will consider the following (binary) arithmetic operators: +, -, *, and /.
You may assume that the expressions you will process are error free. Design a class that stores
the infix and postfix strings. The class must include the following operations:
getInfix: Stores the infix expression.
showInfix: Outputs the infix expression.
showPostfix: Outputs the postfix expression.
convertToPostfix: Converts the infix expression into a postfix expression. The resulting postfix
expression is stored in pfx.
precedence: Determines the precedence between two operators. If the first operator is of higher
or equal precedence than the second operator, it returns the value true; otherwise, it returns the
value false.
A + B - C;
(A + B ) * C;
(A + B) * (C - D);
A + ((B + C) * (E - F) - G) / (H - I);
A + B * (C + D ) - E / F * G + H;
Infix Expression: A+B-C;
Postfix Expression: AB+C-
Infix Expression: (A+B)*C;
Postfix Expression: AB+C*
Infix Expression: (A+B)*(C-D);
Postfix Expression: AB+CD-*
Infix Expression: A+((B+C)*(E-F)-G)/(H-I);
Postfix Expression: ABC+EF-*G-HI-/+
Infix Expression: A+B*(C+D)-E/F*G+H;
Postfix Expression: ABCD+*+EF/G*-H+
PLEASE PROVIDE FOLLOWING.
A UML diagram for your class.
The header file for your class.
The implementation file for your class.
The source code for your test program.
Solution
#include
using namespace std;
const int MAX = 50 ;
class InfixToPostfix
{
private :
char target[MAX], stack[MAX] ;
char *s, *t ;
int top ;
public :
InfixToPostfix( ) ;
void getInfix ( char *str ) ;
void showInfix () ;
void push ( char c ) ;
char pop( ) ;
void convertToPostfix( ) ;
int precedence ( char c ) ;
void showPostfix( ) ;
void Delete();
} ;
InfixToPostfix :: InfixToPostfix( )
{
top = -1 ;
strcpy ( target, \"\" ) ;
strcpy ( stack, \"\" ) ;
t = target ;
s = \"\" ;
}
void InfixToPostfix :: getInfix ( char *str )
{
s = str ;
}
void InfixToPostfix :: showInfix ( )
{
cout<<\"Infix Expression :\"<= precedence ( *s ) )
{
*t = opr ;
t++ ;
opr = pop( ) ;
}
push ( opr ) ;
push ( *s ) ;
}
else
push ( *s ) ;
s++ ;
}
if ( *s == \')\' )
{
opr = pop( ) ;
while ( ( opr ) != \.
A stack is a linear data structure that follows the LIFO (last in, first out) principle. Elements can only be inserted or removed from one end, called the top. Stacks have common operations like push to add an element and pop to remove the top element. Stacks have many applications including evaluating arithmetic expressions in postfix notation, implementing recursion, and solving puzzles like Towers of Hanoi. The document discusses stack implementations using arrays and linked lists and provides examples of stack applications.
*Metamorphosis* is a biological process where an animal undergoes a dramatic transformation from a juvenile or larval stage to a adult stage, often involving significant changes in form and structure. This process is commonly seen in insects, amphibians, and some other animals.
INTRO TO STATISTICS
INTRO TO SPSS INTERFACE
CLEANING MULTIPLE CHOICE RESPONSE DATA WITH EXCEL
ANALYZING MULTIPLE CHOICE RESPONSE DATA
INTERPRETATION
Q & A SESSION
PRACTICAL HANDS-ON ACTIVITY
How to manage Multiple Warehouses for multiple floors in odoo point of saleCeline George
The need for multiple warehouses and effective inventory management is crucial for companies aiming to optimize their operations, enhance customer satisfaction, and maintain a competitive edge.
The *nervous system of insects* is a complex network of nerve cells (neurons) and supporting cells that process and transmit information. Here's an overview:
Structure
1. *Brain*: The insect brain is a complex structure that processes sensory information, controls behavior, and integrates information.
2. *Ventral nerve cord*: A chain of ganglia (nerve clusters) that runs along the insect's body, controlling movement and sensory processing.
3. *Peripheral nervous system*: Nerves that connect the central nervous system to sensory organs and muscles.
Functions
1. *Sensory processing*: Insects can detect and respond to various stimuli, such as light, sound, touch, taste, and smell.
2. *Motor control*: The nervous system controls movement, including walking, flying, and feeding.
3. *Behavioral responThe *nervous system of insects* is a complex network of nerve cells (neurons) and supporting cells that process and transmit information. Here's an overview:
Structure
1. *Brain*: The insect brain is a complex structure that processes sensory information, controls behavior, and integrates information.
2. *Ventral nerve cord*: A chain of ganglia (nerve clusters) that runs along the insect's body, controlling movement and sensory processing.
3. *Peripheral nervous system*: Nerves that connect the central nervous system to sensory organs and muscles.
Functions
1. *Sensory processing*: Insects can detect and respond to various stimuli, such as light, sound, touch, taste, and smell.
2. *Motor control*: The nervous system controls movement, including walking, flying, and feeding.
3. *Behavioral responses*: Insects can exhibit complex behaviors, such as mating, foraging, and social interactions.
Characteristics
1. *Decentralized*: Insect nervous systems have some autonomy in different body parts.
2. *Specialized*: Different parts of the nervous system are specialized for specific functions.
3. *Efficient*: Insect nervous systems are highly efficient, allowing for rapid processing and response to stimuli.
The insect nervous system is a remarkable example of evolutionary adaptation, enabling insects to thrive in diverse environments.
The insect nervous system is a remarkable example of evolutionary adaptation, enabling insects to thrive
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...larencebapu132
This is short and accurate description of World war-1 (1914-18)
It can give you the perfect factual conceptual clarity on the great war
Regards Simanchala Sarab
Student of BABed(ITEP, Secondary stage)in History at Guru Nanak Dev University Amritsar Punjab 🙏🙏
This chapter provides an in-depth overview of the viscosity of macromolecules, an essential concept in biophysics and medical sciences, especially in understanding fluid behavior like blood flow in the human body.
Key concepts covered include:
✅ Definition and Types of Viscosity: Dynamic vs. Kinematic viscosity, cohesion, and adhesion.
⚙️ Methods of Measuring Viscosity:
Rotary Viscometer
Vibrational Viscometer
Falling Object Method
Capillary Viscometer
🌡️ Factors Affecting Viscosity: Temperature, composition, flow rate.
🩺 Clinical Relevance: Impact of blood viscosity in cardiovascular health.
🌊 Fluid Dynamics: Laminar vs. turbulent flow, Reynolds number.
🔬 Extension Techniques:
Chromatography (adsorption, partition, TLC, etc.)
Electrophoresis (protein/DNA separation)
Sedimentation and Centrifugation methods.
The ever evoilving world of science /7th class science curiosity /samyans aca...Sandeep Swamy
The Ever-Evolving World of
Science
Welcome to Grade 7 Science4not just a textbook with facts, but an invitation to
question, experiment, and explore the beautiful world we live in. From tiny cells
inside a leaf to the movement of celestial bodies, from household materials to
underground water flows, this journey will challenge your thinking and expand
your knowledge.
Notice something special about this book? The page numbers follow the playful
flight of a butterfly and a soaring paper plane! Just as these objects take flight,
learning soars when curiosity leads the way. Simple observations, like paper
planes, have inspired scientific explorations throughout history.
Geography Sem II Unit 1C Correlation of Geography with other school subjectsProfDrShaikhImran
The correlation of school subjects refers to the interconnectedness and mutual reinforcement between different academic disciplines. This concept highlights how knowledge and skills in one subject can support, enhance, or overlap with learning in another. Recognizing these correlations helps in creating a more holistic and meaningful educational experience.
Exploring Substances:
Acidic, Basic, and
Neutral
Welcome to the fascinating world of acids and bases! Join siblings Ashwin and
Keerthi as they explore the colorful world of substances at their school's
National Science Day fair. Their adventure begins with a mysterious white paper
that reveals hidden messages when sprayed with a special liquid.
In this presentation, we'll discover how different substances can be classified as
acidic, basic, or neutral. We'll explore natural indicators like litmus, red rose
extract, and turmeric that help us identify these substances through color
changes. We'll also learn about neutralization reactions and their applications in
our daily lives.
by sandeep swamy
Title: A Quick and Illustrated Guide to APA Style Referencing (7th Edition)
This visual and beginner-friendly guide simplifies the APA referencing style (7th edition) for academic writing. Designed especially for commerce students and research beginners, it includes:
✅ Real examples from original research papers
✅ Color-coded diagrams for clarity
✅ Key rules for in-text citation and reference list formatting
✅ Free citation tools like Mendeley & Zotero explained
Whether you're writing a college assignment, dissertation, or academic article, this guide will help you cite your sources correctly, confidently, and consistent.
Created by: Prof. Ishika Ghosh,
Faculty.
📩 For queries or feedback: [email protected]
GDGLSPGCOER - Git and GitHub Workshop.pptxazeenhodekar
This presentation covers the fundamentals of Git and version control in a practical, beginner-friendly way. Learn key commands, the Git data model, commit workflows, and how to collaborate effectively using Git — all explained with visuals, examples, and relatable humor.
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsesushreesangita003
what is pulse ?
Purpose
physiology and Regulation of pulse
Characteristics of pulse
factors affecting pulse
Sites of pulse
Alteration of pulse
for BSC Nursing 1st semester
for Gnm Nursing 1st year
Students .
vitalsign
2. Stack
A linear list which allows insertion and deletion of an element at one end only is
called stack.
The insertion operation is called as PUSH and deletion operation as POP.
The most accessible elements in stack is known as top.
The elements can only be removed in the opposite orders from that in which
they were added to the stack.
Such a linear list is referred to as a LIFO (Last In First Out) list.
… …
TOP
Insertio
n
Deletion
A
B
C
3. Stack Cont…
A pointer TOP keeps track of the top element in the stack.
Initially, when the stack is empty, TOP has a value of “-1”.
Each time a new element is inserted in the stack, the pointer is incremented
by “one” before, the element is placed on the stack.
The pointer is decremented by “one” each time a deletion is made from the
stack.
4. Applications of Stack
Recursion (
https://cdn-media-1.freecodecamp.org/images/1*fsYHEgadIdn0fJt-cBXDHQ.gif)
Keeping track of function calls
Evaluation of expressions
Reversing characters
Servicing hardware interrupts
Solving combinatorial problems using backtracking
Expression Conversion (Infix to Postfix, Infix to Prefix)
Game Playing (Chess)
Microsoft Word (Undo / Redo)
Compiler – Parsing syntax & expression
Finding paths
5. Procedure : PUSH (S, TOP, X)
This procedure inserts an element X to the top of a stack.
Stack is represented by a vector S containing N elements.
A pointer TOP represents the top element in the stack.
1. [Check for stack overflow]
If TOP ≥ N-1
Then write (‘STACK
OVERFLOW’)
Return
2. [Increment TOP]
TOP ← TOP + 1
3. [Insert Element]
S[TOP] ← X
4. [Finished]
Return
S
Stack is empty, TOP = -1,
N=3
PUSH(S, TOP,
10)
TOP =
0
10
PUSH(S, TOP,
8)
TOP =
1
8
PUSH(S, TOP, -
5)
TOP = 2 -5
PUSH(S, TOP, 6)
Overflow
6. Function : POP (S, TOP)
This function removes & returns the top element from a stack.
Stack is represented by a vector S containing N elements.
A pointer TOP represents the top element in the stack.
1. [Check for stack underflow]
If TOP = -1
Then write (‘STACK
UNDERFLOW’)
Return (0)
2. [Decrement TOP]
TOP ← TOP - 1
3. [Return former top element of
stack]
Return(S[TOP + 1])
S
10
8
-5
POP(S, TOP) TOP = 2
TOP =
1
POP(S, TOP)
TOP =
0
POP(S, TOP)
TOP = -
1
POP(S, TOP)
Underflow
7. Function : PEEP (S, TOP, I)
This function returns the value of the Ith
element from the TOP of the stack.
The element is not deleted by this function.
Stack is represented by a vector S containing N elements.
1. [Check for stack underflow]
If TOP-I+1 ≤ -1
Then write (‘STACK
UNDERFLOW’)
Return (0)
2. [Return Ith
element from top
of the stack]
Return(S[TOP–I+1])
S
10
8
-5
TOP = 2
PEEP (S, TOP,
2) 8
PEEP (S, TOP,
3)
10
PEEP (S, TOP,
4)
Underflo
w
8. PROCEDURE : CHANGE (S, TOP, X, I)
This procedure changes the value of the Ith
element from the top of the stack to
X.
Stack is represented by a vector S containing N elements.
1. [Check for stack underflow]
If TOP-I+1 ≤ -1
Then write (‘STACK
UNDERFLOW’)
Return
2. [Change Ith
element from top
of the stack]
S[TOP–I+1] ← X
3. [Finished]
Return
S
10
8
-5
TOP = 2
CHANGE (S, TOP, 50,
2) 50
CHANGE (S, TOP, 9, 3)
9
CHANGE (S, TOP, 25,
8)
Underflow
9. Polish Expression & their Compilation
Evaluating Infix Expression
a + b * c + d * e
1 2
3
4
A repeated scanning from left to right is needed as operators appears inside
the operands.
Repeated scanning is avoided if the infix expression is first converted to an
equivalent parenthesis free prefix or suffix (postfix) expression.
Prefix Expression: Operator, Operand, Operand
Postfix Expression: Operand, Operand, Operator
(a + b) * (c + d) * e
10. Polish Notation
This type of notation is known Lukasiewicz Notation or Polish Notation or
Reverse Polish Notation due to Polish logician Jan Lukasiewicz.
In both prefix and postfix equivalents of an infix expression, the variables are
in same relative position.
The expressions in postfix or prefix form are parenthesis free and operators are
rearranged according to rules of precedence for operators.
11. Polish Notation
Sr. Infix Postfix Prefix
1 a
2 a + b
3 a + b + c
4 a + (b + c)
5 a + (b * c)
6 a * (b + c)
7 a * b * c
a a
a b + + a b
a + b + c a + b + c (ab+)+ c (ab+) c + a b + c +
a b + c + + + a b c
a b c + + + a + b c
a b c * + +a * b c
a b c + * * a + b c
a b *c* ** a b c
12. Finding Rank of any Expression
E = ( A + B * C / D - E + F / G / ( H + I ))
Rank (E) = R(A) + R(+) + R(B) + R(*) + R(C) + R (/) + R(D) + R(-) + R(E) + R(+) + R(F) +
R(/) + R(G) + R(/) + R(H) + R(+) +
R(I)
Note: R = Rank, Rank of Variable = 1, Rank of binary operators = -1
Rank (E) = 1 + (-1) + 1 + (-1) + 1 + (-1) + 1 + (-1) + 1 + (-1) + 1 + (-1) + 1 + (-1) + 1 + (-
1) + 1
Rank (E) = 1
Any Expression is valid if Rank of that
expression is 1
13. Infix and postfix
Conventional notation is called infix notation.
Parentheses are required to specify the order of the
operations. For example: a * b + c
Postfix notation (also known as reverse Polish notation)
eliminates the need for parentheses.
There are no precedence rules to learn, and parentheses are
never needed.
14. Infix to postfix Conversion
Let us use a stack
1. When an operand is read, output it
2. When an operator is read
• Pop until the top of the stack has an element of lower
precedence
• Then push it
3. When ) is found, pop until we find the matching (
4. ( has the lowest precedence when in the stack but has the
highest precedence when in the input
5. When we reach the end of input, pop until the stack is empty
15. Infix to postfix Conversion
Symbol Input
precedence
function (F)
Stack
precedence
function (G)
Rank
function (R)
+, - 1 2 -1
*, / 3 4 -1
^ 6 5 -1
Variabl
es
7 8 1
( 9 0 -
16. infixVect
postfixVect
( a + b - c ) * d – ( e + f )
Infix to postfix conversion
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
17. infixVect
postfixVect
a + b - c ) * d – ( e + f )
(
stackVect
Infix to postfix conversion
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
18. infixVect
postfixVect
+ b - c ) * d – ( e + f )
(
a
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
19. infixVect
postfixVect
b - c ) * d – ( e + f )
(
a
+
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
20. infixVect
postfixVect
- c ) * d – ( e + f )
(
a b
+
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
21. infixVect
postfixVect
c ) * d – ( e + f )
(
a b +
-
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
22. infixVect
postfixVect
) * d – ( e + f )
(
a b + c
-
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
23. infixVect
postfixVect
* d – ( e + f )
a b + c -
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
24. infixVect
postfixVect
d – ( e + f )
a b + c -
*
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
25. infixVect
postfixVect
– ( e + f )
a b + c - d
*
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
26. infixVect
postfixVect
( e + f )
a b + c – d *
-
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
27. infixVect
postfixVect
e + f )
a b + c – d *
-
(
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
28. infixVect
postfixVect
+ f )
a b + c – d * e
-
(
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
29. infixVect
postfixVect
f )
a b + c – d * e
-
(
+
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
30. infixVect
postfixVect
)
a b + c – d * e f
-
(
+
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
31. infixVect
postfixVect
a b + c – d * e f +
-
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
32. infixVect
postfixVect
a b + c – d * e f + -
Infix to postfix conversion
stackVect
Sym
Prece
dence
+, - 2
*, / 4
^ 5
Varia
bles
8
( 0
) -
33. 3 + 4 * 5 / 6
Exercise
(300 + 23) * (43 - 21) / (84 + 7)
(4 + 8) * (6 - 5) / ((3 – 2) * (2 + 2))
((a + b) – c * d + (t * 4))
(((ab + t – 6) * 5) – (5 + x) / z)
Symbol
Stack
precedenc
e
function
(G)
+, - 2
*, / 4
^ 5
Variabl
es
8
( 0
) -
34. Algorithm : REVPOL
Given an input string INFIX containing an infix expression which has been
padded on the right with ‘)’.
This algorithm converts INFIX into reverse polish and places the result in the
string POLISH.
All symbols have precedence value given by the table.
Stack is represented by a vector S, TOP denotes the top of the stack, algorithm
PUSH and POP are used for stack manipulation.
Function NEXTCHAR returns the next symbol in given input string.
The integer variable RANK contains the rank of expression.
The string variable TEMP is used for temporary storage purpose.
35. Infix to postfix Conversion
Symbol Input
precedence
function (F)
Stack
precedence
function (G)
Rank
function (R)
+, - 1 2 -1
*, / 3 4 -1
^ 6 5 -1
Variabl
es
7 8 1
( 9 0 -
37. Input
Symbol
Content of
stack
Reverse
polish
expression
Rank
( a + b ^ c ^ d )
NEXT
( 0
(
4. [Translate the infix expression]
Repeat thru step 7
while NEXT!= ‘)‘
5. [Remove symbols with greater precedence from
stack]
IF TOP < 0
Then write (‘INVALID’)
EXIT
Repeat while G(S[TOP]) > F(NEXT)
TEMP POP (S, TOP)
POLISH POLISH O TEMP
RANK RANK + R(TEMP)
IF RANK < 0
Then write (‘INVALID’)
EXIT
6. [Are there matching parentheses]
IF G(S[TOP]) != F(NEXT)
Then call PUSH (S,TOP, NEXT)
Else POP (S,TOP)
7. [Get next symbol]
NEXT NEXTCHAR(INFIX)
(( 0
a ((a 0
+ (( a 1
((+
b ((+b a 1
^ ((+ ab 2
((+^
c ((+^c ab 2
^ ((+^ abc 3
((+^^
d ((+^^d abc 3
) (( abcd^^+ 1
(
38. 1. [Initialize Stack]
TOP 0
S[TOP] ← ‘(’
2. [Initialize output string and rank
count]
POLISH ‘’
RANK 0
3. [Get first input symbol]
NEXT NEXTCHAR(INFIX)
4. [Translate the infix expression]
Repeat thru step 7
while NEXT != ‘)‘
5. [Remove symbols with greater
precedence from stack]
IF TOP < 0
Then write (‘INVALID’)
EXIT
Repeat while G(S[TOP]) > F(NEXT)
TEMP POP (S, TOP)
POLISH POLISH O TEMP
RANK RANK + R(TEMP)
IF RANK < 0
Then write (‘INVALID’)
EXIT
6. [Are there matching parentheses]
IF G(S[TOP]) != F(NEXT)
Then call PUSH (S,TOP, NEXT)
Else POP (S,TOP)
7. [Get next symbol]
NEXT NEXTCHAR(INFIX)
8. [Is the expression valid]
IF TOP != -1 OR RANK != 0
Then write (‘INVALID‘)
Else write (‘VALID’)
Symbol IPF (F) SPF (G) RF (R)
+, - 1 2 -1
*, / 3 4 -1
^ 6 5 -1
Variables 7 8 1
( 9 0 -
) 0 - -
39. 2
General Infix-to-Postfix Conversion
Create an empty stack called stack for keeping operators. Create an empty list
for output.
Read the character list from left to right and perform following steps
If the character is an operand (Variable), append it to the end of the output list
1
If the character is a left parenthesis ‘(’, push it on the stack
If the character is a right parenthesis ‘)’, pop the stack until the corresponding left
parenthesis ‘)’ is removed. Append each operator to the end of the output list.
3
If the token is an operator, *, /, +, or -, push it on the stack. However, first remove any
operators already on the stack that have higher or equal precedence and append them
to the output list.
4
Infix: ( a + b ^ c ^ d ) * ( e + f / d )
Symbol Input
precedence
function (F)
Stack
precedence
function (G)
Rank
function
(R)
+, - 1 2 -1
*, / 3 4 -1
^, $ 6 5 -1
Variable 7 8 1
Postfix: a b c ^ d ^ + e f d / + *
40. Perform following operations
Convert the following infix expression to postfix. Show the stack contents.
A$B-C*D+E$F/G
A+B–C*D*E$F$G
a+b*c-d/e*h
((a+b^c^d)*(e+f/d))
Convert the following infix expression to prefix.
A + B – C * D * E ^ F ^ G
Step 1: Reverse infix input string
Step 2: Convert reverse infix of step 1 into postfix
Step 3: Reverse postfix expression of step 2
Symbol Input
precedence
function (F)
Stack
precedence
function (G)
Rank
function
(R)
+, - 1 2 -1
*, / 3 4 -1
^, $ 6 5 -1
Variable
s
7 8 1
( 9 0 -
) 0 - -
AB$CD*-EF$G/+
AB+CD*EF$G$*-
abc*+de/h*-
abc^d^+efd/+*
G ^ F ^ E * D * C – B + A
G F ^ E ^ D * C – B * A+
+A * B – C * D ^ E ^ F G
41. Evaluation of postfix expression
Each operator in postfix string refers to the previous two operands in the
string.
Each time we read an operand; we PUSH it onto Stack.
When we reach an operator, its operands will be top two elements on the
stack.
We can then POP these two elements, perform the indicated operation on
them and PUSH the result on the stack so that it will be available for use as an
operand for the next operator.
42. Evaluation of postfix expression
Evaluate Expression: 5 6 2 - +
Empty
Stack Read 5, is it operand?
PUSH
5
Read 6, is it operand?
PUSH
6
Read 2, is it operand?
PUSH
2
Read – , is it operator?
POP two symbols and
perform operation
and PUSH result
Operan
d 1
Operan
d 2
– 5
4
Read + , is it operator?
POP two symbols and
perform operation and
PUSH result
Operan
d 1
Operan
d 2
+
Read next symbol,
if it is end of
string, POP
answer from
Stack
Answe
r
9
43. Algorithm: EVALUATE_POSTFIX
Given an input string POSTFIX representing postfix expression.
This algorithm evaluates postfix expression and put the result into variable
VALUE.
Stack is represented by a vector S, TOP denotes the top of the stack, Algorithm
PUSH and POP are used for stack manipulation.
Function NEXTCHAR returns the next symbol in given input string.
OPERAND1, OPERAND2 and TEMP are used for temporary variables
PERFORM_OPERATION is a function which performs required operation on
OPERAND1 & OPERAND2.
44. Algorithm: EVALUATE_POSTFIX
1. [Initialize Stack]
TOP -1
VALUE 0
2. [Evaluate the postfix expression]
Repeat until last character
TEMP NEXTCHAR (POSTFIX)
If TEMP is DIGIT
Then PUSH (S, TOP, TEMP)
Else OPERAND2 POP (S, TOP)
OPERAND1 POP (S, TOP)
VALUE PERFORM_OPERATION(OPERAND1, OPERAND2, TEMP)
PUSH (S, POP, VALUE)
3. [Return answer from stack]
Return (POP (S, TOP))
46. Algorithm: EVALUATE_PREFIX
Given an input string PREFIX representing prefix expression.
This algorithm evaluates prefix expression and put the result into variable
VALUE.
Stack is represented by a vector S, TOP denotes the top of the stack, Algorithm
PUSH and POP are used for stack manipulation.
Function NEXTCHAR returns the next symbol in given input string.
OPERAND1, OPERAND2 and TEMP are used for temporary variables
PERFORM_OPERATION is a function which performs required operation on
OPERAND1 & OPERAND2.
47. Algorithm: EVALUATE_PREFIX
1. [Initialize Stack]
TOP -1
VALUE 0
2. [Evaluate the prefix expression]
Repeat from last character up to first
TEMP NEXTCHAR (PREFIX)
If TEMP is DIGIT
Then PUSH (S, TOP, TEMP)
Else OPERAND1 POP (S, TOP)
OPERAND2 POP (S, TOP)
VALUE PERFORM_OPERATION(OPERAND1, OPERAND2, TEMP)
PUSH (S, POP, VALUE)
3. [Return answer from stack]
Return (POP (S, TOP))
48. Recursion
A procedure that contains a procedure call to itself or a procedure call to
second procedure which eventually causes the first procedure to be called
is known as recursive procedure.
Two important conditions for any recursive procedure
Each time a procedure calls itself it must be nearer in some sense to a solution.
1
There must be a decision criterion for stopping the process or computation.
2
Two types of recursion
This is recursive defined function.
E.g. Factorial function
Primitive Recursion
This is recursive use of procedure.
E.g. Find GCD of given two numbers
Non-Primitive
Recursion
49. The Towers of Hanoi
• In the great temple of Brahma in Benares, on a brass plate under
the dome that marks the center of the world, there are 64 disks of
pure gold that the priests carry one at a time between these
diamond needles according to Brahma's immutable law:
• No disk may be placed on a smaller disk. In the begging of the
world all 64 disks formed the Tower of Brahma on one needle.
Now, however, the process of transfer of the tower from one needle
to another is in mid course.
• When the last disk is finally in place, once again forming the Tower
of Brahma but on a different needle, then will come the end of the
world and all will turn to dust.
50. Is the End of the World Approaching?
• 64 gold discs
• Given 1 move a second
• Problem complexity 2n
584,942,417,355 years
five hundred eighty-four billion nine hundred forty-two million four
hundred seventeen thousand three hundred fifty-five years
51. The Towers of Hanoi --- A Stack-based Application
• GIVEN: three poles
• a set of discs on the first pole, discs of different sizes, the smallest discs
at the top
• GOAL: move all the discs from the left pole to the right one.
• CONDITIONS: only one disc may be moved at a time.
• A disc can be placed either on an empty pole or on top of a larger disc.
60. Towers of Hanoi – Implementation
using ‘C’
void TOH(int n,char x,char y,char z)
{
if(n>0)
{
count++;
TOH(n-1,x,z,y);
printf("n%c to %c",x,y);
TOH(n-1,z,y,x);
}
}
int main()
{
int n=3;
TOH(n,'A','B','C');
printf(“nTotal steps are %d",count);
}
#include<stdio.h>
int count=0;
62. Algorithm: RECOGNIZE
Write an algorithm which will check that the given string belongs to following
grammar or not.
L= {wcwR
| w Є {a,b}*
} (Where wR
is the reverse of w)
• Given an input string named STRING on the alphabet {a, b, c} which contains a blank in
its rightmost character position.
• Function NEXTCHAR returns the next symbol in STRING.
• This algorithm determines whether the contents of STRING belong to the above
language.
• The vector S represents the stack and TOP is a pointer to the top element of the stack.
Example of valid
strings :
abcb
a
aabbcbb
aa
Example of Invalid
strings:
aabcaa
b
63. L= {wcwR
| w Є {a,b}*
} (Where wR
is the reverse of w)
a b a c a b
a
𝒄
𝒂
𝒃
𝒂
𝒂
𝒃
𝒂
64. Algorithm: RECOGNIZE
Input String: a b c
b a □
Charact
er
Scanne
d
Stack
Content
c
1. [Initialize stack by placing
a letter ‘c’ on the top]
TOP 0
S [TOP] ← ‘c’
0
2. [Get and PUSH symbols until
either c’ or blank is
encountered]
NEXT ← NEXTCHAR (STRING)
Repeat while NEXT ≠ ‘c’
If NEXT = ‘ ‘
Then Write (‘Invalid
String’)
Exit
Else Call PUSH (S, TOP,
NEXT)
NEXT ← NEXTCHAR
(STRING)
a ca
b cab
c cab
NEXT
1
65. Algorithm: RECOGNIZE
b ca
a c
3. Scan characters following ‘c’;
Compare them to the characters on
stack
Repeat While S[TOP] ≠ ‘c’
NEXT ← NEXTCHAR (STRING)
X ← POP (S, TOP)
If NEXT ≠ X
Then Write(‘Invalid String’)
Exit
2
Charact
er
Scanne
d
Stack
Content
c
0
a ca
b cab
c cab
1
Input String: a b c
b a □
NEXT
4. [Next symbol must be blank]
NEXT ← NEXTCHAR (STRING)
If NEXT = ‘ ‘
Then Write (‘VALID STRING’)
Else Write (‘INVALID STRING’) □
66. Algorithm: RECOGNIZE
1. [Initialize stack by placing a
letter ‘c’ on the top]
TOP 0
S [TOP] ← ‘c’
2. [Get and PUSH symbols until
either ‘c’ or blank is
encountered]
NEXT ← NEXTCHAR (STRING)
Repeat while NEXT ≠ ‘c’
If NEXT = ‘ ‘
Then Write (‘Invalid
String’)
Exit
Else Call PUSH (S, TOP,
NEXT)
NEXT ← NEXTCHAR
(STRING)
3. [Scan characters following ‘c’;
Compare them to the characters
on stack]
Repeat While S [TOP] ≠ ‘c’
NEXT ← NEXTCHAR (STRING)
X ← POP (S, TOP)
If NEXT ≠ X
Then Write(‘INVALID STRING’)
Exit
4. [Next symbol must be blank]
NEXT ← NEXTCHAR (STRING)
If NEXT = ‘ ‘
Then Write (‘VALID STRING’)
Else Write (‘INVALID STRING’)
5. [Finished]
Exit
67. Algorithm : RECOGNIZE
Write an algorithm to determine if an input character string is of the form ai
bi
where i>=1
i.e. number of a should be equal to no of b
68. Algorithm to find factorial using recursion
Given integer number N
This algorithm computes factorial of N.
Stack S is used to store an activation record associated with each recursive call.
TOP is a pointer to the top element of stack S.
Each activation record contains the current value of N and the current return
address RET_ADDE.
TEMP_REC is also a record which contains two variables PARAM & ADDRESS.
Initially return address is set to the main calling address. PARAM is set to
initial value N.
69. Trace of Algorithm FACTORIAL, N=2
Enter Level
1
(main call)
Step 1: PUSH (S,0,(N=2, main
address))
Step 2: N!=0
PARAM N-1 (1), ADDR
Step 3
2
Main
Address
TOP
Enter Level 2
(first recursive
call)
Step 1: PUSH (S,1,(N=1, step 3))
Step 2: N!=0
PARAM N-1 (3), ADDR
Step 3
2
Main
Address
1
Step
3
TOP
Enter Level 3
(second
recursive
call)
Step 1: PUSH (S,2,(N=0, step 3))
Step 2: N=0
FACTORIAL 1
2
Main
Address
1
Step
3
0
Step
3
TOP
Step 4: POP(A,3)
GO TO Step 3 2
Main
Address
1
Step
3
TOP
Level
Number
Description Stack
Content
70. Trace of Algorithm FACTORIAL, N=2
Return to
Level 2
Step 3: FACTORIAL 1*1
Step 4: POP (A,2)
GO TO Step 3
2
Main
Address
TOP
Return to
Level 1
Step 3: FACTORIAL 2*1
Step 4: POP (A,1)
GO TO Main Address
TOP = 0
Level
Number
Description Stack
Content
71. Algorithm: FACTORIAL
1. [Save N and return Address]
CALL PUSH (S, TOP, TEMP_REC)
2. [Is the base criterion found?]
If N=0
then FACTORIAL 1
GO TO Step 4
Else PARAM N-1
ADDRESS Step 3
GO TO Step 1
3. [Calculate N!]
FACTORIAL N * FACTORIAL
4. [Restore previous N and return address]
TEMP_REC POP(S,TOP)
(i.e. PARAM N, ADDRESS RET_ADDR)
GO TO ADDRESS