0% found this document useful (0 votes)
47 views33 pages

Unit Two

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views33 pages

Unit Two

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Unit Two

The Stack
What is Stack??
• A stack is a linear data structure in which the insertion of a new element and
removal of an existing element takes place at the same end represented as the top
of the stack.
• To implement the stack, it is required to maintain the pointer to the top of the
stack, which is the last element to be inserted because we can access the elements
only on the top of the stack.
• Stack has one end, whereas the Queue has two ends (front and rear). It contains
only one pointer top pointer pointing to the topmost element of the stack.
Whenever an element is added in the stack, it is added on the top of the stack, and
the element can be deleted only from the stack. In other words, a stack can be
defined as a container in which insertion and deletion can be done from the one
end known as the top of the stack.
Some key points related to stack
• It is called as stack because it behaves like a real-world stack, piles of books, etc.
• A Stack is an abstract data type with a pre-defined capacity, which means that it
can store the elements of a limited size.
• It is a data structure that follows some order to insert and delete the elements, and
that order can be LIFO or FILO.
Basic Operations on Stack
• In order to make manipulations in a stack, there are certain operations provided to
us.
• push() to insert an element into the stack
• pop() to remove an element from the stack
• top() Returns the top element of the stack.
• isEmpty() returns true if stack is empty else false.
• size() returns the size of stack.
Stack as ADT
• In Stack ADT Implementation instead of data being stored in each node, the pointer to data is
stored.
• The program allocates memory for the data and address is passed to the stack ADT.
• The head node and the data nodes are encapsulated in the ADT. The calling function can only
see the pointer to the stack.
• The stack head structure also contains a pointer to top and count of number of entries
currently in stack.
• push() – Insert an element at one end of the stack called top.
• pop() – Remove and return the element at the top of the stack, if it is not empty.
• peek() – Return the element at the top of the stack without removing it, if the stack is not
empty.
• size() – Return the number of elements in the stack.
• isEmpty() – Return true if the stack is empty, otherwise return false.
• isFull() – Return true if the stack is full, otherwise return false.
Implementation of Stack
Steps:
1. Initially, we get empty stack. The top of an empty stack is set to -1.
2. Next, we push an element into the stack. The top of the stack will now point to the element
just pushed.
3. Whenever, we push element into the stack, the top is incremented so as to point to the
recent element.
4. Whenever a pop operation is performed, the top element is removed from the stack and top
is decrement to point to the next element.
5. If the stack becomes empty, the top will be set to -1.
• A stack data structure can be implemented using a one-dimensional array. But stack
implemented using array stores only a fixed number of data values.

Stack Operations using Array


A stack can be implemented using array as follows.
Before implementing actual operations, first follow the below steps to create an empty stack.
• Step 1 - Include all the header files which are used in the program and define a
constant 'SIZE' with specific value.
• Step 2 - Declare all the functions used in stack implementation.
• Step 3 - Create a one dimensional array with fixed size (int stack[SIZE])
• Step 4 - Define a integer variable 'top' and initialize with '-1'. (int top = -1)
• Step 5 - In main method, display menu with list of operations and make suitable function
calls to perform operation selected by the user on the stack.
push(value) - Inserting value into the stack
• In a stack, push() is a function used to insert an element into the stack. In a stack, the new
element is always inserted at top position. Push function takes one integer value as
parameter and inserts that value into the stack. We can use the following steps to push an
element on to the stack...
• Step 1 - Check whether stack is FULL. (top == SIZE-1)
• Step 2 - If it is FULL, then display "Stack is FULL!!! Insertion is not possible!!!" and
terminate the function.
• Step 3 - If it is NOT FULL, then increment top value by one (top++) and set stack[top] to
value (stack[top] = value).
pop() - Delete a value from the Stack
• In a stack, pop() is a function used to delete an element from the stack. In a stack, the element
is always deleted from top position. Pop function does not take any value as parameter. We
can use the following steps to pop an element from the stack...
• Step 1 - Check whether stack is EMPTY. (top == -1)
• Step 2 - If it is EMPTY, then display "Stack is EMPTY!!! Deletion is not possible!!!" and
terminate the function.
• Step 3 - If it is NOT EMPTY, then delete stack[top] and decrement top value by one (top--).

display() - Displays the elements of a Stack


• We can use the following steps to display the elements of a stack...
• Step 1 - Check whether stack is EMPTY. (top == -1)
• Step 2 - If it is EMPTY, then display "Stack is EMPTY!!!" and terminate the function.
• Step 3 - If it is NOT EMPTY, then define a variable 'i' and initialize with top.
Display stack[i] value and decrement i value by one (i--).
• Step 3 - Repeat above step until i value becomes '0'.
Static Stack Implementation

Algorithm InitializeEmptyStack(S)
1. Start
2. Assign the value to top to -1. ie S->top = -1
3. Stop

Algorithm isFull(S)
4. Start
5. Check if the top of S is equal to MAX-1, return true
ie
if(s->top == MAX-1)
return true;
6. Else return false
7. Stop
Algorithm isEmpty(S)
1. Start
2. Check if the top of S is equal to -1, return true
ie
if(S->top == -1)
return true;
3. Else return false
4. Stop
Applications
Stack is used directly and indirectly in the following fields:
● To evaluate the expressions (postfix, prefix)
● To keep the page-visited history in a Web browser
● To perform the undo sequence in a text editor
● Used in recursion
● To pass the parameters between the functions in a C program
● Can be used as an auxiliary data structure for implementing algorithms
● Can be used as a component of other data structures
Stack Implementation

Steps:
1. Initially, we get empty stack. The top of an empty stack is set to -1.
2. Next, we push an element into the stack. The top of the stack will
now point to the element just pushed.
3. Whenever, we push element into the stack, the top is incremented so
as to point to the recent element.
4. Whenever a pop operation is performed, the top element is removed
from the stack and top is decrement to point to the next element.
5. If the stack becomes empty, the top will be set to -1.
Continued….
Infix, Prefix and Postfix Notation

• One of the applications of the stack is to evaluate the arithmetic expression.


• We can represent the arithmetic expressions following three types of notation:

Infix Prefix Postfix


• Infix expression: It is an ordinary mathematical notation of expression where
operator is written in between the operands.
Example: A+B. Here ‘+’ is an operator and A and B are called operands
• Prefix notation: In prefix notation the operator precedes the two operands. That
is the operator is written before the operands. It is also called polish notation.
Example: +AB
• Postfix notation: In postfix notation the operators are written after the operands
so it is called the postfix notation (post mean after). In this notation the operator
follows the two operands.
Example: AB+
• Both prefix and postfix are parenthesis free expressions.
Examples
● Examples: [find the types]
○ A+ B
○ + AB
○ AB +
○ (A + B) * C
○ *+ABC
○ AB+ C*
Infix to Postfix Conversion

 First convert the sub-expression to postfix that is to be evaluated first and repeat
this process.
 Substitute intermediate postfix sub-expression by any variable whenever
necessary that makes it easy to convert.
 To convert an infix expression to its postfix equivalent:
 We first convert the innermost parentheses to postfix, resulting as a new
operand
 In this fashion parenthesis can be successively eliminated until the entire
expression is converted
 The last pair of parenthesis to be opened within a group of parenthesis
encloses the first expression within the group to be transformed
 This last in, first-out behavior suggests the use of a stack
Precedence rule:

 While converting infix to postfix you have to consider the precedence rule, and
the precedence rules are as follows:
 Exponentiation ( the expression AB is A raised to the B power, so that 32
=9)
 Multiplication/Division
 Addition/Subtraction
 When un-parenthesized operators of the same precedence are scanned, the order
is assumed to be left to right except in the case of exponentiation, where the
order is assumed to be from right to left.
 A+B+C means (A+B)+C
 A^B^C means A^(B^C)
 By using parenthesis we can override the default precedence. Ex: A + (B* C).
Rules for the conversion from infix to postfix expression
1. Print the operand as they arrive.
2. If the stack is empty or contains a left parenthesis on top, push the incoming
operator on to the stack.
3. If the incoming symbol is '(', push it on to the stack.
4. If the incoming symbol is ')', pop the stack and print the operators until the left
parenthesis is found.
5. If the incoming symbol has higher precedence than the top of the stack, push it on
the stack.
6. If the incoming symbol has lower precedence than the top of the stack, pop and print
the top of the stack. Then test the incoming operator against the new top of the stack.
7. If the incoming operator has the same precedence with the top of the stack then use
the associativity rules. If the associativity is from left to right then pop and print the
top of the stack then push the incoming operator. If the associativity is from right to
left then push the incoming operator.
8. At the end of the expression, pop and print all the operators of the stack.
Use the following rule to convert it in postfix:
1. Parenthesis for emphasis
2. Convert the multiplication
3. Convert the addition
4. Post-fix form

A + (B * C). Infix form


=>A + (B * C)
=>A + (BC*) Convert the Multiplication
=>A (BC*) + Convert the addition
=>ABC*+ Post-fix form
Algorithm Tracing: Infix Expression - ((A-(B+C))*D)$(E+F)
Assignment:
Infix to Prefix Conversion
 The precedence rule is same as that of previous case; only change is that the
operator is placed before the operands rather than after them.
 The prefix of
A+B-C is -+ABC. Ex:
 Ex: A $ B * C – D + E / F / (G + H)
 A+B-C (infix) => A $ B * C – D + E / F /(+GH)
=> $AB* C – D + E / F /(+GH)
 =>(+AB)-C
=> *$ABC-D+E/F/(+GH)
 => -+ABC (prefix) => *$ABC-D+(/EF)/(+GH)
=> *$ABC-D+//EF+GH
=> (-*$ABCD) + (//EF+GH)
=> +-*$ABCD//EF+GH
Rules for converting infix to prefix
1. first, reverse the infix expression given in the problem.
2. Scan the expression from left to right.
3. Whenever the operands arrive, print them.
4. If the operator arrives and the stack is found empty, then simply push the
operator into the stack.
5. If the incoming operator has higher precedence with a TOP of the stack, push
the incoming operator into the stack.
6. If the incoming operator has same precedence with the TOP of the stack, push
the incoming operator into the stack.
7. If the incoming operator has lower precedence than the TOP of the stack, pop
and print the TOP of the stack. Test the incoming operator against the TOP of
the stack again and pop the operator from the stack till it finds the operator of a
lower precedence or same precedence.
8. If the incoming operator has the same precedence with the TOP of the stack and
the incoming operator is ^, then pop the top of the stack till the condition is true. If
the condition is not true, push the ^ operator.
9. When we reach the end of the expression, pop and print all the operators from the
TOP of the stack.
10. If the operator is ‘)’, then push it into the stack.
11. If the operator is ‘(’, then pop all the operators from the stack till it finds )
opening bracket in the stack.
12. If the TOP of the stack is ‘)’, push the operator on the stack.
13. At the end, reverse the output.
Algorithm
● Step 1: Reverse the infix expression. Note that while reversing the infix
expression, the left and right parentheses are interchanged.
● Step 2: Obtain the postfix expression of the input expression as obtained in [1].
● Step 3: Reverse the postfix expression to obtain the prefix expression.

● Ex: Infix expression: (A+B$C)*D+E$5


● String reversal => 5$E+D*(C$B+A)
● Obtaining the postfix expression of the given infix as:
5E$DCB$A+*+
● Reverse the result to get prefix expression:
+*+A$BCD$E5
Assignment
Evaluating Postfix Expression:

Algorithm
1. Add the unique symbol # at the end of array pstack.
2. Scan the symbol of postfix expression one by one from the left to right.
3. Do the following with each symbol until # is encountered:
a. If the symbol is operand, push into stack.
b. If the symbol is operator, the pop last 2 elements of the stack and evaluate it
as :
Pstack[top-1] operator pstack[top]
Push the result into the stack
4. Pop the element of the stack which will be the value of evaluation of postfix
expression.
Ex: Evaluation of

ABCD$+*EF$GH/*-

Where A=4,B=5, C=4,


D=2, E=2, F=2, G=9 & F=3

DO THIS:
123+*321-+* => ??
• Let us now consider another example. Suppose that we are asked to evaluate the
following postfix expression:
623 + — 382 -f-* 2$ 3 +
• We show the contents of the stack opndstk and the variables .cvnib, opndl , opnd2,
and value after each successive iteration of the loop. The top of opndstk is to the
right.
Evaluation of prefix expression

Algorithm:
1. Begin with initializing opndstack as an empty operand stack.
2. Scan infix expression one char at a time from right to left.
3. Do the following until no more characters in infix expressions.
a. If the scan char is operand, push it to opndstack
b. If the scan char is operator, pop opndstack[top] and opndstack[top-1] and
perform the specified operation as:
Opndstack[top] operator opndstack[top-1]
Push the result into stack
4. Pop opndstack and display the required value.
• Ex: -*+4325 PERFORM THIS:

You might also like