0% found this document useful (0 votes)
17 views

CACS201 Unit 2 - The Stack

Uploaded by

Mizash Kandel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

CACS201 Unit 2 - The Stack

Uploaded by

Mizash Kandel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Unit 2

The Stack
Contents
• Introduction
• Stack as an ADT
• POP and PUSH Operation
• Stack Application
• Evaluation of Infix, Postfix and Prefix Expressions
• Conversion of Expression
Introduction
• A Stack is a linear collection of data elements
in which the element inserted last will be the
element taken out first (i.e., a stack is a LIFO
data structure).
• A stack is open only from one end.
• The stack is a linear data structure in which
the insertion, as well as deletion of an
element, is done only from the end called
TOP.
• One end is always closed, and the other end
is used to insert and remove data.
• Stacks can be implemented by using arrays or
linked lists.
Stack as an ADT
• A stack contains elements of the same type arranged in sequential
order and push and pop operations occur at one end at the top of the
stack. The following operations may be carried out on the stack:
• Push () – Insert an item on one end of the stack called the top.
• Pop () – Removes and returns the item to the top of the stack, if it is not
empty.
• Top () – Returns the element to the top of the stack without deleting it, if the
stack is not empty.
• Size () – Returns the number of items within the stack.
• IsEmpty () – Returns true if it is empty, otherwise returns false.
• IsFull () – Returns true if the stack is full or returns false.
Primitive Operations on Stack
1. To create a stack: Create a stack in memory. Creation of stack can be
done either using arrays or using linked lists.
2. To insert an element onto the stack that is push operation
3. To delete an element from stack that is the pop operation
4. To verify which element is at the top of the stack
5. To verify whether a stack is empty or full.
PUSH Operation
• Push operation is the process of adding new elements in the stack.
• However, before inserting any new element in the stack, we must
always check for the overflow condition, which occurs when we try to
insert an element in the stack which is already full.
• An overflow condition can be checked as follows, If TOP = MAX – 1,
where MAX is the size of the stack.
• Hence, if the overflow condition is true, then an overflow message is
displayed on the screen; otherwise, the element is inserted into the
stack.
PUSH Operation Example

After inserting 10 in it, the new stack will be:


Algorithm for a Push Operation in a Stack
Step 1: START
Step 2: IF TOP = MAX – 1
Print OVERFLOW ERROR
Go to Step 5
[End of If]
Step 3: Set TOP = TOP + 1
Step 4: Set STACK[TOP] = ITEM
Step 5: EXIT
POP Operation
• The pop operation is the process of removing elements from the
stack.
• However, before deleting an element from the stack, we must always
check for the underflow condition, which occurs when we try to
delete an element from the stack which is already empty.
• An underflow condition can be checked as follows, If TOP = NULL.
• Hence, if the underflow condition is true, then an underflow message
is displayed on the screen; otherwise, the element is deleted from the
stack.
Pop Operation Example
Algorithm for a Pop Operation in a Stack
Step 1: START
Step 2: IF TOP = NULL
Print UNDERFLOW ERROR
Go to Step 5
[End of If]
Step 3: Set ITEM = STACK[TOP]
Step 4: Set TOP = TOP – 1
Step 5: EXIT
Peek Operation
• Peek is an operation that returns the value of the topmost element of
the stack.
• It does so without deleting the topmost element of the array.
• However, the peek operation first checks for the underflow condition.
• An underflow condition can be checked as follows, If TOP = NULL.
• Hence, if the underflow condition is true, then an underflow message
is displayed on the screen; otherwise, the value of the element is
returned.
Write a menu-driven program implementing a
stack performing push and pop operations in
C using array.
Stack Application (1/2)
• Expression Evaluation: In expression evaluation, stack is used.
• Expression Conversion
• a. Infx to postfx conversion:
• (a + b) * (c - d) given infx notation is converted into postfx form a b + c d -* using operator and operand
stack.
• b. Infx to prefx conversion:
• (a + b) * (c -d) given infx notation is converted into prefx form * + a b - c d using operator and operand
stack.
• c. Postfx to infx conversion:
• AB-C*
• Backtracking: Backtracking is used in algorithms where there are steps along a
certain path from a point of departure to a certain target.
• Function Call and Function Return Process: For maintaining function call data
stack data structure is used.
• Recursive Functions: Recursion uses stack memory to store intermediate results
of all local variables for that particular function call.
Stack Application (2/2)
• Depth First Search (DFS): Stack data structure is used in DFS.
• Undo Mechanism in Text Editors: It is implemented using stack data
structure.
• Reverse the String: In reverse string application we first push all characters
in a string on the stack and then pop the characters from the stack gives
you reverse string.
• Towers of Hanoi Problems: It is solved by using stack.
• Parsing or Syntax Analysis: Parsing or syntax analysis is the process of
analyzing whether a string of formal language statements conforms to the
grammar or not. For this purpose, we have to create a parse tree or
derivation tree, and in this parsing or syntax analysis, we have to use stack
data structure.
Infix, Postfix and Prefix Expressions
• Infix Notation
• We write expression in infix notation, e.g. a - b + c, where operators are used in-between
operands.
• It is easy for us humans to read, write, and speak in infix notation but the same does not go well
with computing devices.
• An algorithm to process infix notation could be difficult and costly in terms of time and space
consumption.
• Prefix Notation
• In this notation, operator is prefixed to operands, i.e. operator is written ahead of operands.
• For example, +ab.
• This is equivalent to its infix notation a + b.
• Prefix notation is also known as Polish Notation.
• Postfix Notation
• This notation style is known as Reversed Polish Notation.
• In this notation style, the operator is postfixed to the operands i.e., the operator is written after
the operands.
• For example, ab+.
• This is equivalent to its infix notation a + b.
Difference in Infix, Postfix and Prefix Expressions
Why Postfix/Prefix Expressions are faster than Infix?

• For Infix Expression which is format A+B*C, if the compiler is reading


left to right then it can’t evaluate A+B first until it has read whole
expression and knows expression is actually A + (B*C) i.e. B * C needs
to be implemented first
• Postfix for above infix is ABC*+. Now, as soon as compiler sees two
operands followed by operator it can implement it without caring for
precedence.
• Assume ABC*+
• ABC*+ (BC* is implemented as B*C and result is put back)
• AX+ (Assuming X stores result of BC* i.e. B*C)
• Now finally AX+ can be implemented as A+X
Why Postfix/Prefix Expressions are faster than Infix?

• Compiler converts our Infix Expression into postfix or Prefix as


expressions are operated as stacks and postfix and prefix are faster to
implement as compiler doesn't need to care about precedence at all.
• Compiler converts infix expression to postfix/prefix at compile time,
so at runtime your calculations are always happening in post-prefix. A
website's code maybe compiled once a week but it may need to run 1
million times a week.
• Which is why we prefer that runtime execution should be as fast as
possible.
Conversion of Infix Expression to Postfix Expression

• We can convert an infix expression to a postfix expression using a stack.


• First, we start to scan the expression from left side to right side.
• In an expression, there may be some operators, operands, and parentheses.
Hence, we have to keep in mind some of the basic rules which are:
• Each time we encounter an operand, it is added directly to the postfix expression.
• Each time we get an operator, we should always check the top of the stack to check the
priority of the operators.
• If the operator at the top of the stack has higher precedence or the same precedence as that
of the current operator, then, in that case, it is repeatedly popped out from the stack and
added to the postfix expression. Otherwise, it is pushed into the stack.
• Each time when an opening parenthesis is encountered, it is directly pushed into the stack,
and similarly, if a closing parenthesis is encountered, we will repeatedly pop out from the
stack and add the operators in the postfix expression. Also, the opening parenthesis is
deleted from the stack.
Algorithm to Convert Infix Expression to Postfix Expression

Step 1: START
Step 2: Add “)” parenthesis to the end of infix expression.
Step 3: Push ’(’ parenthesis on the stack.
Step 4: Repeat the steps until each character in the infix expression is scanned.
a) IF “(” parenthesis is found, push it onto the stack.
b) If an operand is encountered, add it to the postfix expression.
c) IF “)” parenthesis is found, then follow these steps –
- Continually pop from the stack and add it to the postfix expression until a “(” parenthesis is encountered.
- Eliminate the “(” parenthesis.
d) If an operator is found, then follow these steps –
- Continually pop from the stack and add it to the postfix expression which has same or high precedence than
the current operator.
- Push the current operator to the stack.
Step 5: Continually pop from the stack to the postfix expression until the stack becomes empty.
Step 6: EXIT
Conversion of Infix Expression to Postfix Expression Example

• (A + B) *C / D
Convert
[((A +B) * (C – D)) + (F – G)]
to postfix expression.
Convert the following infix expression into a postfix
expression.
(A + B) ^ C – (D * E) / F
Write a program to convert an infix expression
to a postfix expression.
Algorithm to Convert Infix Expression to Prefix Expression

Step 1: START
Step 2: Reverse the infix expression. Also, interchange left and right
parenthesis on reversing the infix expression.
Step 3: Obtain the postfix expression of the reversed infix expression.
Step 4: Reverse the postfix expression so obtained in Step 3. Finally, the
expression is converted into prefix expression.
Step 5: EXIT
Conversion of Infix Expression to Prefix Expression Example

• (X - Y) / (A + B)
• After reversing the given infix
expression (B + A) / (Y – X)
• Find the postfix expression of
(B + A) / (Y – X)
• Conversion as shown here ->
• Now, reverse the postfix
expression so obtained, that
is, –X/Y+AB
• Hence, the prefix expression
is –X/Y+AB
Convert (X – Y / Z) * (A / B – C) to prefix
• After reversing the given infix
expression (C – B / A) * (Z / Y – X)
• Find the postfix expression of (C – B /
A) (Z / Y – X)
• ->
• Now, reverse the postfix expression so
obtained, that is, *–X/ZY-/ABC
• Hence, the prefix expression is *–
X/ZY-/ABC
Write a program to convert an infix expression
to a prefix expression.
Evaluation of a Postfix Expression
• With the help of stacks, any postfix expression can easily be
evaluated.
Evaluate the following postfix expressions
234+*5678+*++
Write a program for evaluation of a postfix
expression.
Evaluation of a Prefix Expression
Evaluate the given prefix expressions + - 4 6 * 9 /10 50
Write a program for evaluation of a prefix
expression.

You might also like