DSA Chap 3.pptxDSA Chap 3.pptxDSA Chap 3.pptxDSA Chap 3.pptxDSA Chap 3.pptxDSA Chap 3.pptxDSA Chap 3.pptxDSA Chap 3.pptxDSA Chap 3.pptxDSA Chap 3.pptxDSA Chap 3.pptxDSA Chap 3.pptxDSA Chap 3.pptxDSA Chap 3.pptxDSA Chap 3.pptx
Stack
• Stack isA data structure in which insertion and deletion
occur at the same end (TOP) is called a stack.
• It is a LIFO (Last In First Out) structure.
• The operations of insertion and deletion are called PUSH
and POP.
• Push - push (put) item onto stack
• Pop - pop (get) item from stack
Data Structure and Algorithm
Stack
Data Structure andAlgorithm
push()
push()
pop()
pop()
Remove ‘A’
Remove ‘B’
Insert ‘B’ in the stack
Insert ‘A’ in the stack
Definition
• Stack is a “Last in First Out” data structure, which means
elements inserted are popped in the reversed order
Insert ‘A’
Insert ‘B’
Remove ‘B’
Remove ‘A’
Stack
• A stackis a homogeneous collection of elements in which an
element may be inserted or deleted only at one end, called
the top of the stack.
• Stack is a collection of similar data items in which both
insertion and deletion operations are performed based on
LIFO principle”.
Data Structure and Algorithm
13.
Stack Usage
❖ Bothhardware and software stacks have been used to support four
major computing areas in computing requirements:
▪ function calls
▪ expression evaluation
▪ subroutine return address storage(always called subtask)
▪ dynamically allocated local variable storage
▪ subroutine parameter passing.
Data Structure and Algorithm
14.
ARRAY REPRESENTATION OFSTACKS
• In the computer’s memory, stacks can be represented as a
linear array.
• Every stack has a variable called TOP associated with it,
which is used to store the address of the topmost element
of the stack. It is this position where the element will be added
to or deleted from.
• There is another variable called MAX, which is used to store
the maximum number of elements that the stack can hold.
Data Structure and Algorithm
Operations on aStack
• These are the basic operations that can be performed on a
stack. Assume Maximum size of n.
• Push : This operation adds or pushes another item onto the
stack. The number of items on the stack is less than n.
• Pop: This operation removes an item from the stack. The
number of items on the stack must be greater than 0.
• Top: This operation returns the value of the item at the top of
the stack. Note: It does not remove that item.
• Is Empty: This operation returns true if the stack is empty and
false if it is not.
• Is Full: This operation returns true if the stack is full and false
if it is not.
Data Structure and Algorithm
17.
Push Operation
•The pushoperation is used to insert an element into the stack.
•The new element is added at the top most position of the stack.
•However, before inserting the value, we must first check if
•TOP=MAX–1, because if that is the case, then the stack is full
and no more insertions can be done.
•If an attempt is made to insert a value in a stack that is already
full, an OVERFLOW message is printed
Data Structure and Algorithm
18.
Push Operation
•
To insertan element with value 6, we first check if TOP=MAX–1.
• If the condition is false, then we increment the value of TOP and
store the new element at the position given by stack[TOP]. Thus,
• the updated stack becomes as shown in Fig. 7.6.
Data Structure and Algorithm
19.
Pushing
Data Structure andAlgorithm
• If ITEM=80 is to be inserted, then TOP=TOP+1=4
• STACK[TOP]:= STACK[4]:= ITEM=80
• N=5
• MAXSTACK=10
top = 3 N = 4
17 23 97 44
0 1 2 3 4 5 6 7 8 9
STACK
0 1 2 3 4 5 6 7 8 9
top = 4 N = 5
17 23 97 44
STACK 80
20.
Push Operation
1.push():When anelement 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().
Data Structure and Algorithm
21.
Push Operation
Algorithm: Procedurefor push():
Step 1: START
Step 2: if top>=size-1 then
Write “ Stack is Overflow”
Step 3: Otherwise
3.1: read data value ‘x’
3.2: top=top+1;
3.3: stack[top]=x;
Step 4: END
Data Structure and Algorithm
22.
Push Operation
void push()
{
intx;
if(top >= n-1)
{
cout<<"Stack Overflow..";
return;
}
else
{
cout<<"Enter data: ";
cin<<x;
stack[top] = x;
top = top + 1;
cout<<"Data Pushed into the
stack";
}
}
Data Structure and Algorithm
23.
Pop Operation
• Thepop operation is used to delete the topmost element from
the stack.
• However, before deleting the value, we must first check if
TOP=NULL because if that is the case, then it means the
stack is empty and no more deletions can be done. If an
attempt is made to delete a value from a stack that is
already empty, an UNDERFLOW message is printed.
Data Structure and Algorithm
24.
Pop Operation
Data Structureand Algorithm
• If ITEM=80 is to be deleted, then ITEM:=STACK[TOP]=
STACK[4]= 80
• TOP=TOP-1=3
• N=4
• MAXSTACK=10
top = 3 N = 4
17 23 97 44
0 1 2 3 4 5 6 7 8 9
STACK
0 1 2 3 4 5 6 7 8 9
top = 4 N = 5
17 23 97 44
STACK 80
25.
Pop Operation
2.Pop(): Whenan 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().
Data Structure and Algorithm
26.
Pop Operation
Algorithm: procedurepop():
Step 1: START
Step 2: if top==-1 then
Write “Stack is Underflow”
Step 3: otherwise
3.1: print “deleted element”
3.2: top=top-1;
Step 4: END
Data Structure and Algorithm
Application Areas ofStack
Some stack applications include:
• Evaluating Postfix expression
• Convert infix expression to postfix
• Convert infix expression to Prefix
• Function call ( creates new instance of return addresses for
each call to a function)
• To reverse a word. You push a given word to stack - letter by
letter - and then pop letters from the stack.
Data Structure and Algorithm
30.
Application Areas ofStack
• An "undo" mechanism in text editors; this operation is
accomplished by keeping all text changes in a stack
• Backtracking (game playing, finding paths, exhaustive
searching)
• Memory management, run-time environment for nested
language features
• Parsing
• Recursive Function
Data Structure and Algorithm
31.
Evaluation of AlgebraicExpressions
Humans usually write algebraic expressions
like this:
a + b
This is called infix notation, because the operator (“+”) is inside
the expression
A problem is that we need parentheses or precedence rules to
handle more complicated expressions:
a + b * c = (a + b) * c ?
= a + (b * c) ?
2 + 3 * 4
4 / 2 * 6
Data Structure and Algorithm
32.
Infix, postfix, andprefix notation
There is no reason we can’t place the operator somewhere
else.
infix notation:
a + b
prefix notation:
+ a b
postfix notation:
a b +
Data Structure and Algorithm
Prefix notation was introduced by the
Polish logician Lukasiewicz, and is
sometimes called “Polish notation”
Postfix notation is sometimes called
“reverse Polish notation” or RPN
33.
Infix, postfix, andprefix notation
Question: Why would anyone ever want to use anything so
“unnatural,” when infix seems to work just fine?
Answer: With postfix and prefix notations,
parentheses are no longer needed!
infix postfix prefix
(a + b) * c a b + c * * + a b c
a + (b * c) a b c * + + a * b c
Data Structure and Algorithm
34.
The valuable aspectof postfix
• Parentheses are unnecessary
• Easy for a computer (compiler) to evaluate an arithmetic
expression Postfix (Reverse Polish Notation)
• Fairly simple algorithm exists to evaluate such expressions
based on using a stack
Data Structure and Algorithm
Binary operators: +, -, *, /, etc.,
Unary operators: unary minus, square
root, sin, cos, exp, etc.,
35.
Postfix Evaluation
• Postfixnotation
• In postfix notation, the operator comes after its operands.
Postfix notation is also known as reverse Polish
• notation (RPN) and is commonly used because it enables
easy evaluation of expressions.
• Syntax : operand1 operand2 operator
• Example : AB+C*DEF+/-
Data Structure and Algorithm
36.
Postfix Evaluation
Example 7.1:Convert the following infix expressions into postfix
expressions
• Solution
• (a) (A–B) * (C+D)
• [AB–] * [CD+]
• AB–CD+*
• (b) (A + B) / (C + D) – (D * E)
• [AB+] / [CD+] – [DE*]
• [AB+CD+/] – [DE*]
• AB+CD+/DE*–
Data Structure and Algorithm
37.
Postfix Evaluation UsingStack
Consider the postfix expression :
6 5 2 3 + 8 * + 3 + *
Data Structure and Algorithm
So for evaluating 6 5 2 3 + 8 * + 3 + *
the first item is a value (6) so it is pushed onto the stack
the next item is a value (5) so it is pushed onto the stack
the next item is a value (2) so it is pushed onto the stack
the next item is a value (3) so it is pushed onto the stack
and the stack becomes
38.
Postfix Evaluation UsingStack
Data Structure and Algorithm
the remaining items are now: + 8 * + 3 + *
So next a '+' is read (a binary operator), so
3 and 2 are popped from the stack and their
sum '5' is pushed onto the stack:
39.
Postfix Evaluation UsingStack
Data Structure and Algorithm
Next 8 is pushed and the next item is the operator *:
Postfix Evaluation UsingStack
Data Structure and Algorithm
Next is operator +, so 3 and 45 are popped and
45+3=48 is pushed
Next is operator *, so 48 and 6 are popped, and
6*48=288 is pushed
Converting Infix toPostfix (RPN) conversion
The rules to be remembered during infix to postfix conversion are:
1. Parenthesize the expression starting from left to right.
2. During parenthesizing the expression, the operands associated with
operator having higher precedence are first parenthesized. For e
xample in the above expression B * C is parenthesized first before A
+ B.
3. The sub-expression (part of expression), which has been converted into
postfix, is to be treated as single operand.
4. Once the expression is converted to postfix form, remove the
Data Structure and Algorithm
45.
Converting Infix toPostfix (RPN) conversion
Converting
from infix notation to postfix notation
Assume that your infix expression is of the
form
<identifier> <operator> <identifier>
A postfix expression is created by rewriting
this as
<identifier> <identifier> <operator>
Data Structure and Algorithm
46.
Converting Infix toPostfix (RPN) conversion
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, put it in the postfix exp
3. Otherwise, do the following
1. If the precedence of the current scanned operator is higher than
the precedence of the operator on top of the stack, or if the stack
is empty, or if the stack contains a ‘(‘, then push the current
operator onto the stack.
2. Else, pop all operators from the stack that have precedence
higher than or equal to that of the current operator. After that
push the current operator onto the stack.
4. If the scanned character is a ‘(‘, push it to the stack.
5. If the scanned character is a ‘)’, pop the stack and output it until a ‘(‘
is encountered, and discard both the parenthesis.
6. Repeat steps 2-5 until the infix expression is scanned.
Data Structure and Algorithm
Stack
What is thepostfix form of the following expression?
1. A + ( (B + C) + (D + E) * F ) / G ?
ABC + DE + F * + G / +
2. (A + B) * C - (D - E) * (F + G)?
AB + C * DE - FG + * -
Note: Postfix notation is of little use unless there is an easy method
to convert standard (infix) expressions to postfix. Again a simple
algorithm exists that uses a stack.
Data Structure and Algorithm
49.
Converting Infix toPostfix (RPN) conversion
• Consider the following arithmetic infix expression P
P = A + (B / C - (D * E ^ F ) + G ) * H
Data Structure and Algorithm
Converting Infix toPostfix (RPN) conversion
How does the above algorithm convert the
following arithmetic infix expression
P = A * B + C * D
in to postfix expression?
Data Structure and Algorithm
52.
Converting Infix toPostfix (RPN) conversion
• a
Data Structure and Algorithm
53.
Exercise:
1) Convert thefollowing infix expressions to their postfix
equivalents:
(a) A – B + C (b) A * B + C / D
(b) (A – B ) + C * D / E – C
(c) (A * B) + (C / D) – ( D + E)
Data Structure and Algorithm
54.
Prefix
• Polish Notation(prefix) : Polish notation, also known as
prefix notation, is a form of notation for logic, arithmetic, and
algebra. Its distinguishing feature is that it places operators
to the left of their operands.
• Lacking parentheses or other brackets.
• Syntax : operator operand1 operand2
• Example : -*+ABC/D+EF
Data Structure and Algorithm
55.
Prefix
• Example 7.2Convert the following infix expressions into prefix
expressions
• Solution
• (a) (A + B) * C
• (+AB)*C
• *+ABC
• (b) (A–B) * (C+D)
• [–AB] * [+CD]
• *–AB+CD
• (c) (A + B) / ( C + D) – ( D * E)
• [+AB] / [+CD] – [*DE]
• [/+AB+CD] – [*DE]
• –/+AB+CD*DE
Data Structure and Algorithm