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

Stacks

Uploaded by

abhirampidikilla
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)
23 views

Stacks

Uploaded by

abhirampidikilla
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/ 34

ICS 121 Data Structures I

Module 1 – Stack and Its Applications

Dr Athira B
Assistant Professor
Department of Computer Science and Engineering
IIIT Kottayam
Data Structures
A data structure is a data organization, management, and storage format that
enables efficient access and modification.

Types
Linear and Non Linear Data Structures
Linear Data Structures Non Linear Data Sructures
In a linear data structure, data elements are arranged in a In a non-linear data structure, data elements are attached
linear order where each and every elements are attached in hierarchically manner.
to its previous and next adjacent.
In linear data structure, single level is involved. Whereas in non-linear data structure, multiple levels are
involved.
Its implementation is easy in comparison to non-linear While its implementation is complex in comparison to
data structure. linear data structure.
In linear data structure, data elements can be traversed in While in non-linear data structure, data elements can’t be
a single run only. traversed in a single run only.
In a linear data structure, memory is not utilized in an While in a non-linear data structure, memory is utilized
efficient way. in an efficient way.
Its examples are: array, stack, queue, linked list, etc. While its examples are: trees and graphs.

Applications of linear data structures are mainly in Applications of non-linear data structures are in Artificial
application software development. Intelligence and image processing.
Difference between abstract and concrete data
type
Abstract data type is a type (or class) of objects whose behavior is defined
by a set of values and a set of operations. The user interacts with the
interface, using the operations that have been specified by the abstract
data type. It offers a high level use of a concept independent of it’s
implementation. They package data structure and operations on them
hiding internal details.
Eg: stack, queue
A concrete data type is a data type whose representation is known.
Concrete data types or structures (CDT’s) are direct implementations of a
relatively simple concept.
Arrays, structure, etc.
Stack
• A stack is an Abstract Data Type (ADT), commonly used in most
programming languages.
• It is named stack as it behaves like a real-world stack.
• Example – a deck of cards or a pile of plates.
Examples of stack
• Stack allows operations at one end only
• At any given time, we can only access the top element of a stack.
• This feature makes it LIFO data structure.
• LIFO stands for Last-in-first-out.
• The element which is placed last, is accessed first.
• In stack terminology, insertion operation is called PUSH operation
and removal operation is called POP operation.
Stack Representation
Operations on stack
• Push()-insertion
• Pop()-deletion
• Let Stack[ ] is the stack.
• Top is the integer denoting top index of the stack.
• N is the size of the stack.
Push()
Push()
• We cannot insert elements into a stack which is already filled.
• Hence before insertion we need to check whether the stack is full or
not.
• The condition where stack is full is called overflow.
• If the stack is not full push the element into the stack.
• Top=-1 initially
Checking for
stackFull() push()
int stackFull() void push(int item)
{
{
if(!stackFull())
if (Top>=N-1) {
return 1; stack[++top]=item
else }
else
return 0;
{
} printf(“Stack overflow”);
}
}
Pop()
• We can delete only from a non empty stack.
• Hence before deletion we need to check whether the stack is empty
or not.
• The condition where stack is empty is called underflow.
Pop Operation
Checking for stackEmpty() Pop()
Void pop()
int stackEmpty()
{
{
if(!StackEmpty())
if (Top==-1) {
return 1; return stack[top];
else top=top-1
return 0 }
} else
printf(“Stack underflow”);
}
Applications:
• Temporary storage structure for recursive operations
• Auxiliary storage structure for nested operations, function calls, deferred/postponed
functions
• Manage function calls
• Evaluation of arithmetic expressions in various programming languages
• Conversion of infix expressions into post fix expressions
• Checking syntax of expressions in a programming environment
• Matching of parenthesis
• String reversal
• In all the problems solutions based on backtracking.
• Used in depth first searching graph and tree traversal.
• Operating System functions
• UNDO and REDO functions in an editor.
• Advantages of Stack
• A Stack helps to manage the data in the ‘Last in First out’ method.
• When the variable is not used outside the function in any program, the Stack
can be used.
• It allows you to control and handle memory allocation and deallocation.
• It helps to automatically clean up the objects.

• Disadvantages of Stack
• It is difficult in Stack to create many objects as it increases the risk of the Stack
overflow.
• It has very limited memory.
• In Stack, random access is not possible.
Matching Paranthesis

• For every open paranthesis `(', there exists a following `)'.


• Examples
(())
(())(())
)(
()(
Multiple Paranthesis Matching

• Same as the previous problem, except we have ( ), { } and [ ].


• Examples
• [{()}]
• [{}({})]
• [{]}
Stacks - Recursion
recurse (int n) {
if (n > 1) recurse (n-1);
printf("%d", n);
}

recurse(int 3) {
if (3 > 1) recurse (3-1);
printf("%d", 3);
}
recurse(int 1) {
if (1 > 1) recurse (1-1);
printf("%d", 1); recurse(int 2) {
if (2 > 1) recurse (2-1);
printf("%d", 2);
}

recurse(int 3) {
if (3 > 1) recurse (3-1);
printf("%d", 3);
}
• Print - 1 2 3
Infix, Prefix and Postfix Expressions
Infix
Postfix
operand operator operand
operand operand operator
A+B
A+B+C AB+
A *( B + C * D ) + E AB+ C+

Prefix ABCD * + * E+

Operator operand operand


+AB
 Convert an expression from one form to another form
like Infix to Postfix, Infix to Prefix, Prefix to Postfix and
+AB + C vice versa.

* + * CDBA + E
Solving Postfix

• Solve 2 3 + 4 5 + *
• Answer:45

• Postfix Expression Evaluation:


• Read all the symbols one by one from left to right in the given Postfix
Expression
• If the reading symbol is operand, then push it onto the Stack.
• If the reading symbol is operator(+,- * , / etc. , ) , then perform TWO pop
operations and store the two popped operands in two different variables
(operand1 and operand2) . Then perform reading symbol operation using
operand1 and operand2 and push result back onto the Stack.
• Finally! perform a pop operation and display the popped value as final result.
Infix to Postfix
• Rules
• Input Operand Print
• Input Operator + Empty Stack Push Operator
• End of Input Empty Stack
• Input Operator <= Stack Operator Pop and Print
• Input Operator > Stack Operator Push Operator
• Open Paranthesis put in stack
• Closed Paranthesis Pop and Print till Open Paranthesis

• The Order of Operators according to their preference : * , / , + , - , =


Infix to Postfix Conversion using Stack :

•Scan input string from left to right character by character


•If the character is an operand, put it into postfix expression.
•If the character is an operator and operator's stack is empty, push operator into operators' stack.
•If the operator's stack is not empty, there may be following possibilities.
• If the precedence of scanned operator is greater than the top most operator of operator's
stack, push this operator into operator 's stack.
• If the precedence of scanned operator is less than the top most operator of operator's stack,
pop the operators from operator's stack until we find a low precedence operator than the
scanned character.
• If the precedence of scanned operator is equal then check the associativity of the operator.
• If associativity left to right then pop the operators from stack until we find a low precedence
operator.
• If associativity right to left then simply put into stack. If the scanned character is opening
round bracket ( '(' ), push it into operator's stack.
• If the scanned character is closing round bracket ( ')' ), pop out operators from operator's
stack until we find an opening bracket ('(' ).
•Now pop out all the remaining operators from the operator's stack and push into postfix
expression.
Practice problems
• A + B*C +D = ABC * + D +
• (A + B) * (C + D) = AB + CD + *
• ((A + B) * C) ^ (D + E) / (F – G) = AB + C *DE + ^ FG - /
Infix to Prefix Conversion using Stack :
•Reverse the given expression
•Scan the characters of the given expression from left to right.
•If the character is an operand, put it into prefix expression.
•If the character is an operator and operator's stack is empty, push operator into operators' stack.
•If the operator's stack is not empty, there may be following possibilities.
If the precedence of scanned operator is greater than the top most operator of operator's stack, push this operator
into operator 's stack.
If the precedence of scanned operator is less than the top most operator of operator's stack, pop the operators from
operator's stack until we find a low precedence operator than the scanned character.
If the precedence of scanned operator is equal then check the associativity of the operator. If associativity left to
right then simply put into stack.
If associativity right to left then pop the operators from stack until we find a low precedence operator.
If the character is opening round bracket ( '(' ), push it into operator's stack.
If the character is closing round bracket ( ')' ), pop out operators from operator's stack until we find an opening
bracket ('(' ).
•Repeat Step 2,3 and 4 till expression has character
•Now pop out all the remaining operators from the operator's stack and push into expression.
•Reverse the expression –Prefix expression.
• Infix: A+(B*C)
• Reverse the infix expression
• (C*B)+A
• Then do as before in the case of postfix expression using stack:
Output: CB*A+
• Reverse the final expression Prefix: +A*BC
Practice problems

• Example 2: (A+B)*(C-D) Answer : *+AB-CD


• Example 3: A+(B*C+D)/E Answer : +A/+*BCDE
• Example 4: (A+B/C+D*(E-F)^G) Answer : +A+/BC*D^-EFG
• Example 5: a+b*(c^d-e)^(f+g*h)-I Answer : +a-*b^-^cde+f*ghi
Prefix Expression Evaluation:
• Convert 5+(4*3) to prefix.
• prefix expression: +5*4 3
• Read all the symbols one by one from right to left in the given prefix
Expression
• If the reading symbol is operand, then push it onto the Stack.
• If the reading symbol is operator(+,- , * , / etc . , ) , then perform TWO pop
operations and store the two popped operands in two different variables
(operand1 andoperand2 ) . Then perform reading symbol operation using
operand1 and operand2 and push result back onto the Stack.
• Finally! Perform a pop operation and display the popped value as final result.
Prefix to Postfix expression conversion:
• Scan the prefix expression from right to left, i.e., reverse.
• If the incoming symbol is an operand then push it into the stack.
• If the incoming symbol is an operator then pop two operands from the stack. Once the
operands are popped out from the stack, we add the incoming symbol after the
operands. When the operator is added after the operands, then the expression is
pushed back into the stack.
• Once the whole expression is scanned, pop and print the postfix expression from the
stack.
Postfix to Prefix expression Conversion:
• Scan the postfix expression from left to right.
• If the element is an operand, then push it into the stack.
• If the element is an operator, then pop two operands from the stack.
• Create an expression by concatenating two operands and adding operator before the
operands.
• Push the result back to the stack.
• Repeat the above steps until we reach the end of the postfix expression.
• 5+(4*3)
• Find its postfix and convert to prefix.
• Then, Convert prefix to postfix
• Infix to postfix
Do all these cases with:
• Infix to prefix (A+B) * (C+D)
• Postfix evaluation (2+3) * (5+4)
• Prefix evaluation
• Postfix to prefix
• Prefix to postfix.
• Lab1
1. Write a program to implement stack using array. Perform push and
pop operations
2. Write a program to print the numbers as 10, 40, 30, 20 using stack.
Input is 20, 10, 30, 40.
3. Write a program to match the parenthesis ( { ( ) ] ) using stack.
4. Write a program to solve the expression 5 6 + 3* 1 1 + ^ 2 3 - /

You might also like