0% found this document useful (0 votes)
7 views55 pages

Chapter 4 STACK

Chapter 4 discusses stacks as a data structure that operates on a last-in, first-out (LIFO) principle, detailing its definition, operations, and implementations using arrays and linked lists. It covers fundamental operations such as push, pop, and supportive operations like isEmpty and isFull, along with various applications including expression conversion and evaluation. The chapter also introduces Polish notation for simplifying arithmetic expressions and outlines the process for converting infix expressions to postfix and prefix forms.

Uploaded by

ayantuhacalu
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)
7 views55 pages

Chapter 4 STACK

Chapter 4 discusses stacks as a data structure that operates on a last-in, first-out (LIFO) principle, detailing its definition, operations, and implementations using arrays and linked lists. It covers fundamental operations such as push, pop, and supportive operations like isEmpty and isFull, along with various applications including expression conversion and evaluation. The chapter also introduces Polish notation for simplifying arithmetic expressions and outlines the process for converting infix expressions to postfix and prefix forms.

Uploaded by

ayantuhacalu
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/ 55

CHAPTER 4

DATA STRUCTURES AND ALGORITHMS

STACK
DATA
STRUCTURE
DATA STRUCTURE A N D 1
ALGORITHM
CONTENTS
◾ Stack Definition,
◾ Stack Operations,
◾ Stack Implementation
 using array,
 using linked lists,

◾ Applications of Stacks,
◾ Polish Notation and Expression Conversion
 infix, postfix and prefix expressions using stack,

◾ Recursive Functions
DATA STRUCTURE A N D 2
ALGORITHM
4.1. STACK
◾ A stack is a list with the restriction that insertions and deletions can be performed in
only one position, namely, the end of the list, called the top.
◾ A stack is also an Abstract Data Type (ADT), commonly used in most programming
languages.
◾ It is named stack as it behaves like a real-world stack,
◾ for example – a deck of cards or a pile of plates, stack of chairs etc.

DATA STRUCTURE A N D 3
ALGORITHM
STACK ADT
◾ Stack ADT allows all data operations at one end only.
 At any given time, we can only access the top element of a stack.
◾ Each stack ADT has a data member, commonly named as top, which
points to the topmost element in the stack.
◾ The fundamental operations on a stack are
 push, which is equivalent to an insert, and
 pop, which deletes the most recently inserted element.
◾ In a stack, the element deleted from the set is the one most recently
inserted:
 the stack implements a last-in, first-out, or LIFO, policy.

DATA STRUCTURE A N D 4
ALGORITHM
• A stack can be implemented by means of Array, Structure, Pointer, and Linked List.
• Stack can either be a fixed size one or it may have a sense of dynamic resizing.
5

DATA STRUCTURE A N D
ALGORITHM
4.2. STACK OPERATIONS
 Basic Operations
 Push - Pushing (storing) an element on the stack.
 Pop - Removing (accessing) an element from the stack.
 Supportive operations
 GetTop - reads (only reading, not deleting) an element from the top of the stack
 Stack_initialization - sets up the stack in an empty condition
 isEmpty - checks whether the stack is empty
 isFull - checks whether the stack is full

DATA STRUCTURE A N D 6
ALGORITHM
PUSH OPERATION
֎ Push Operation
◾ The process of putting a new data element onto stack is known as a
Push Operation.
◾ Push operation involves a series of steps −
Step 1 − Checks if the stack is full.
Step 2 − If the stack is full, produces an error and exit.
Step 3 − If the stack is not full, increments top to point next empty space.
Step 4 − Adds data element to the stack location, where top is pointing.
Step 5 − Returns success.

DATA STRUCTURE A N D 7
ALGORITHM
POP OPERATION
֎ Pop Operation
◾ Accessing the content while removing it from the stack, is known as a Pop Operation.
 Array vs linked list ?
◾ A Pop operation may involve the following steps
Step 1 − Checks if the stack is empty.
Step 2 − If the stack is empty, produces an error and exit.
Step 3 − If the stack is not empty, accesses the data element at which
top is pointing.
Step 4 − Decreases the value of top by 1.
Step 5 − Returns success.

DATA STRUCTURE A N D 8
ALGORITHM
GetTop
◾ This returns the top element of the stack without actually popping it.
◾ Gives information about the topmost element.
• The top is still set to the same element (no change)
• This is the key difference between the pop and getTop operations.

DATA STRUCTURE A N D 9
ALGORITHM
isEmpty

◾ Simply tests whether the stack is empty or not.


◾ This operation is useful as a safeguard against an attempt to pop an element from
an empty stack.
◾ Popping an empty stack is an error condition known as stack underflow.

DATA STRUCTURE A N D 10
ALGORITHM
isFull
◾ In ideal conditions, stacks should possess infinite capacity so that the subsequent
elements can always be pushed, regardless of the number of elements already present
on the stack.

◾ However, computers always have finite memory capacity, and we do need to check

the stack_full condition before doing push operation.


◾ Pushing an element in a full stack is an error condition know as stack overflow.
◾ Simply tests whether the stack is full or not.

DATA STRUCTURE A N D 11
ALGORITHM
4.3. STACK IMPLEMENTATION
◾ Can be implemented using both a static data structure (array) and a dynamic data
structure (linked list).
◾ Array implementation
• The simplest way to represent a stack is by using a one-dimensional array.
• A stack implemented using an array is also called a contiguous stack.
• It is very simple to manage a stack when represented using an array. (ordered elements)
• The only difficulty with an array is its static memory allocation.

DATA STRUCTURE A N D 12
ALGORITHM
STACK IMPLEMENTATION (USING ARRAY)
◾ One of the two sides of the array can be considered as the top (upper) side and the
other as the bottom (lower)
◾ the upper side is most commonly used
◾ The first element is stored at Stack[0], the second element at Stack[1]…..last Stack[n-
1]
◾ Associated with the array will be an integer variable, top, which points to the top
element in the stack.
◾ The initial value of top is -1 when the stack is empty.
◾ It can hold the elements from index 0, and can grow to a maximum of n - 1 as this is a
static stack using arrays.

DATA STRUCTURE A N D 13
ALGORITHM
STACK IMPLEMENTATION (USING LINKED LIST)

◾ In linked list implementation of stack, the nodes are maintained


non contiguous in the memory.
◾ Stack is said to be overflown if the space left in the memory is
not enough to create a node.

DATA STRUCTURE A N D 14
ALGORITHM
ADDING A NODE TO THE STACK (PUSH OPERATION)
◾ Pushing an element to a stack in linked list implementation is different
from that of an array implementation.
◾ In order to push an element onto the stack, the following steps are
involved.
1. Create a node first and allocate memory to it.
2. If the list is empty then the item is to be pushed as the start node of the
list. This includes assigning value to the data part of the node and assign
null to the address part of the node.

3. If there are some nodes in the list already, then we have to add the new
element in the beginning of the list (to not violate the property of the
stack). For this purpose, assign the address of the starting element to
the address field of the new node and make the new node, the starting 15

node of the list.


DATA STRUCTURE A N D
ALGORITHM
DATA STRUCTURE A N D 16
ALGORITHM
DELETING A NODE FROM THE STACK (POP
OPERATION)
◾ Deleting a node from the linked list implementation of stack is different from that in the

array implementation. In order to pop an element from the stack, we need to follow the
following steps

1. Check for the underflow condition: The underflow condition occurs when we try to pop
from an already empty stack. The stack will be empty if the head pointer of the list points
to null.

2. Adjust the head pointer accordingly: In stack, the elements are popped only from one
end, therefore, the value stored in the head pointer must be deleted and the node must
be freed. The next node of the head node now becomes the head node.
17

DATA STRUCTURE A N D
ALGORITHM
DISPLAY THE NODES (TRAVERSING)
◾ Displaying all the nodes of a stack needs traversing all the nodes of the linked list
organized in the form of stack. For this purpose, we need to follow the following
steps.
1. Copy the head pointer into a temporary pointer.

2. Move the temporary pointer through all the nodes of the list and print the value field
attached to every node.

DATA STRUCTURE A N D 18
ALGORITHM
4.4. APPLICATION OF STACK

• Used in a wide range of applications


1. Converting infix expression to postfix and prefix expressions
2. Evaluating the postfix expression
3. Checking well-formed (nested) parenthesis
4. Reversing a string
5. Processing function calls
6. Parsing (analyze the structure) of computer programs
7. Simulating recursion
8. In computations such as decimal to binary conversion
9. In backtracking algorithms (often used in optimizations and in games)

DATA STRUCTURE A N D 19
ALGORITHM
EXPRESSION EVALUATION AND CONVERSION

◾ The most frequent application of stacks is in the evaluation of arithmetic expressions.


◾ An arithmetic expression is made of operands, operators, and delimiters.
◾ How to generate machine language instructions that could properly evaluate any arithmetic
expression? X = (A/B + C x D - F x G/Q) the order in which the operations are to be carried out?
◾ Might have several meanings, and even if the meanings were uniquely defined, it is still

difficult to generate a correct and reasonable instruction sequence.


◾ Fortunately, with the help of stack we can solve the problem in both elegant and simple way.

DATA STRUCTURE A N D 20
ALGORITHM
POLISH NOTATION AND EXPRESSION CONVERSION

◾ The Polish Mathematician Jan Lukasiewicz suggested a notation called Polish notation,

which gives two alternatives to represent an arithmetic expression, namely the postfix and
prefix notations.
◾ The fundamental property of Polish notation is that the order in which the operations are to be

performed is determined by the positions of the operators and operands in the expression.
◾ Hence, the advantage is that parentheses is not required while writing expressions in Polish

notation.

DATA STRUCTURE A N D 21
ALGORITHM
CONT.…
◾ The conventional way of writing the expression is called infix, because the binary operators
occur between the operands, and unary operators precede their operand.
◾ For example, the expression ((A + B) x C)/D is an infix expression.

◾ In postfix notation, the operator is written after its operands, whereas in prefix notation,

the operator precedes its operands.

DATA STRUCTURE A N D M 2
ALGORITH 2
NEED FOR PREFIX AND POSTFIX EXPRESSIONS
◾ Evaluation of an infix expression using a computer needs proper code generation by the

compiler without any ambiguity and is difficult because of various aspects such as the
operator’s priority and associativity.
◾ The postfix and prefix expressions possess many advantages as follows:
1. The need for parenthesis as in an infix expression is overcome in postfix and prefix
notations.
2. The priority of operators is no longer relevant.
3. The order of evaluation depends on the position of the operator but not on priority and
associativity.
4. The expression evaluation process is much simpler than attempting a direct evaluation from
the infix notation.
23

DATA STRUCTURE A N D
ALGORITHM
A2: POSTFIX EXPRESSION EVALUATION

DATA STRUCTURE A N D 24
ALGORITHM
AN EXAMPLE POSTFIX EXPRESSION E = AB + Cx#.

DATA STRUCTURE A N D 25
ALGORITHM
MANUALLY CONVERTING AN EXPRESSION

1. Initially, fully parenthesize the given infix expression. Use operator precedence and
associativity rules for the same.

2. Now, move all operators so that they replace their corresponding right/left parenthesis.

3. Finally, delete all parentheses, and we get the postfix/prefix expression.

DATA STRUCTURE A N D 26
ALGORITHM
EXAMPLE: MANUALLY CONVERTING INFIX TO POSTFIX
◾ E = A/B ^ C + D \ E - A \ C

1. Let us fully parenthesize the same as

◾ E = (((A/(B ^ C)) + (D \ E)) - (A \ C))

2. Let us move all operators to the corresponding right parenthesis and replace the same.

3. Now let us eliminate all parentheses. We get the postfix equivalent of the infix expression.
◾ E(postfix) = ABC ^/ DE x+ AC x -

DATA STRUCTURE A N D 27
ALGORITHM
EXAMPLE: MANUALLY CONVERTING INFIX TO PREFIX
◾ E = A/B ^ C + D \ E - A \ C

1. Let us fully parenthesize the same as


◾ E = (((A/(B ^ C)) + (D \ E)) - (A \ C))

2. Let us move all operators to the corresponding right parenthesis and replace the same.

3. Now let us eliminate all parentheses. We get the prefix equivalent of the infix expression.
◾ E(prefix) = - +/ A ^ BC x DE x AC

DATA STRUCTURE A N D 28
ALGORITHM
ALGORITHM TO CONVERT AN INFIX TO A POSTFIX (ALSO
TO PREFIX)
◾ The order of the operand remains the same in the infix and the postfix notations.(from
observation)
◾ The sequence of operands, output postfix = input infix expression.
◾ Hence, the operands from the infix expression can be immediately sent to the output as
they occur.

◾ To handle the operators, the operands are stored in the stack until the right moment and

they are unstacked (removed from the stack); they are then passed to the output.
◾ Try 1
• If in stack operator priority is greater than the incoming operator, pop the operator
otherwise push it

DATA STRUCTURE A N D 29
ALGORITHM
EXAMPLE 1 (Testing)
◾ Let E be an infix expression as E = A + B x C#
◾ After conversion, the expression should yield ABCx+, that is, the sequence of stacking them
should be as

How to handle
ALGORITHM
brackets ?
DATA STRUCTURE A N D 3
0
EXAMPLE 2 (Testing)
◾ The infix expression A x (B + C) x D, after conversion, should generate the postfix expression
ABC +x Dx,

DATA STRUCTURE A N D 31
ALGORITHM
EXAMPLE 3 (Testing)

◾ E=AxB+
C#.

DATA STRUCTURE A N D 32
ALGORITHM
EXCERSICE
◾ Convert the following infix expressions to their equivalent postfix expression, show
the sequence of push and pop operations.
1.
2.

3. AX () X G

DATA STRUCTURE A N D 33
ALGORITHM
EXAMPLE 4 (Testing)

◾X = A ^ B ^
C

◾ If we use the previous rule, do we get the correct postfix


expression?

DATA STRUCTURE A N D 34
ALGORITHM
SOLUTION
◾ We must take into account the associativity of operators and prepare a hierarchy scheme
for the binary arithmetic operators and delimiters.

◾ When an operator is at the top of the stack or in an expression (current token), they are
to be treated with different priorities.

◾ Hence, each operator is to be assigned two priorities—the incoming priority (ICP) and the
in-stack priority (ISP).

◾ In previous examples, we observed that the lower priority operators should spend more time
in the stack and the higher priority operators should be popped out earlier.
◾ To achieve this, we need to assign the appropriate ICPs and ISPs to the operators.
DATA STRUCTURE A N D 35
ALGORITHM
Points to be Taken into Consideration While Assigning
ICPs & ISPs:
1. Higher priority operators should be assigned higher values of ISP and ICP.

2. For right associative operators, ISP should be lower than ICP. For example, A ^ B ^ C should
generate ABC^^, which means (A) ^ (B ^ C).
3. If ICP is higher than ISP, the operator should be stacked.
4. The ISP and ICP should be equal for left associative operators.

DATA STRUCTURE A N D 36
ALGORITHM
SUMMING UP
• The following are the steps involved in the evaluation of an expression.
1. Assign priorities to all operators and define associativity (left or right).
2. Assign appropriate values of ICPs and ISPs accordingly.
• For left associative operators, assign equal ISP and ICP.
• For right associative operators, assign higher ICP than ISP. For example, assign a higher ICP
for ‘^’.
3. Scan the expression from left to right, character by character, till the end of expression.
4. If the character is an operand, then display the same.
5. If the character is an operator and if ICP > ISP then push the operator
else
while(ICP <= ISP)
pop the operator and display it.
end while
Stack the incoming operator
6. Continue till end of expression
• The expression could be in one of the three forms—infix, postfix, or prefix. 3
7

DATA STRUCTURE A N D
ALGORITHM
INFIX TO POSTFIX CONVERSION ALGORITHM

DATA STRUCTURE A N D 38
ALGORITHM
◾ Convert the following infix

expression to its postfix


form:

DATA STRUCTURE A N D 39
ALGORITHM
INFIX TO PREFIX CONVERSION ALGORITHM
◾ For converting the infix expression to a prefix expression, two stacks are needed—the operator
Stack and the display Stack. The display Stack stores the prefix expression.

DATA STRUCTURE A N D 40
ALGORITHM
DATA STRUCTURE A N D 41
ALGORITHM
◾ Convert the following

infix expression to its


prefix form:

DATA STRUCTURE A N D 42
ALGORITHM
POSTFIX TO INFIX CONVERSION ALGORITHM

DATA STRUCTURE A N D 43
ALGORITHM
◾ Convert the following

postfix expression to
its infix form:

DATA STRUCTURE A N D 44
ALGORITHM
POSTFIX TO PREFIX CONVERSION ALGORITHM

DATA STRUCTURE A N D 45
ALGORITHM
◾ Convert the following

postfix expression to
its prefix form:

DATA STRUCTURE A N D 46
ALGORITHM
PREFIX TO INFIX CONVERSION ALGORITHM

DATA STRUCTURE A N D 47
ALGORITHM
PREFIX TO POSTFIX CONVERSION ALGORITHM

DATA STRUCTURE A N D 48
ALGORITHM
A3: CHECKING CORRECTNESS OF WELL-FORMED
PARENTHESES
◾ Consider a mathematical expression that includes several sets of nested parentheses. For
example, Z – ((X ((X + Y/J – 2)) + Y)/3).
◾ To ensure that the parentheses are nested correctly, we need to check that
1. There are equal numbers of right and left parentheses
2. Every right parenthesis is preceded by a matching left parenthesis.
◾ To solve this problem, let us define the parentheses count = the number of left parenthesis
minus the number of right parenthesis
◾ The two conditions that must hold if the parentheses in an expression form an admissible
pattern are as follows:
1. The parenthesis count at each point in the expression is non-negative.
2. The parenthesis count at the end of the expression is 0.

DATA STRUCTURE A N D 49
ALGORITHM
CONT.…
◾ A stack may also be used to keep track of the parentheses count.

◾ Whenever a left parenthesis is encountered, it is pushed onto the stack, and whenever a

right parenthesis is encountered, the stack is examined.


◾ If the stack is empty, then the string is declared to be invalid.

◾ In addition, when the end of the string is reached, the stack must be empty; otherwise, the

string is declared to be invalid.

DATA STRUCTURE A N D 50
ALGORITHM
A4: REVERSING A STRING WITH A STACK
◾ Suppose a sequence of elements is presented and it
is desired to reverse the sequence.
◾ Various methods could be used for this, and in
the beginning, the programmer will usually
suggest a solution using an array.
◾ A conceptually simple solution, however, is
based on using a stack.
◾ The LIFO property of the stack access guarantees
the reversal.
◾ Suppose the sequence ABCDEF is to be reversed.

DATA STRUCTURE A N D 51
ALGORITHM
A5: PROCESSING OF FUNCTION CALLS
◾ The processing of function calls and their terminations can be controlled with stacks
easily & efficiently.
◾ The program must remember the place where the call was made so that it can return there after
the function is complete.
◾ The sequence by which a function actively proceeds is summed up as the LIFO or FILO
property

52

DATA STRUCTURE A N D
ALGORITHM
A7: RECURSION
◾ In C/C++, a function can call itself, that is, one of the statements of the function is a call to
itself.
◾ Such functions are called recursive functions and can be used to implement recursive
problems in an elegant manner.
◾ To solve a recursive problem using functions, the problem must have an end condition that
can be stated in non-recursive terms.

53

DATA STRUCTURE A N D
ALGORITHM
A7: Cont.. .

◾ Recursion is a technique that allows us to break down a problem into one or more sub-

problems that are similar in form to the original problem.


◾ Recursive programs are most inefficient as regards their name and space complexities.

◾ Hence, there is a need to convert them into iterative ones. To achieve this conversion stacks

need to be used.

DATA STRUCTURE A N D 54
ALGORITHM
A8: CONVERTING DECIMAL NUMBERS TO BINARY
◾ To convert a number from decimal to binary, we simply divide the number by 2 until a quotient

of 0 is reached.
◾ Then, use the successive remainders in reverse order as the binary representation.
◾ For example, to convert decimal 35 to binary, we perform the following computation:

We need some intermediate storage that will hold the


result and finally send the output as the correct result.

If we store every bit generated in a stack, we will get the


correct result at the end. This is because the working
behavior of the stack is LIFO.

55

DATA STRUCTURE A N D
ALGORITHM

You might also like