Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

DS Unit-3 R23

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

UNIT-IIⅠ

STACKS

Stack:
● Stack is a linear data structure in which insertion and
deletion can perform at the same end called top of
stack.

● When an item is added to a stack, the operation is


called push, and when an item is removed from the
stack the operation is called pop.

● Stack is also called as Last-In-First-Out (LIFO) list


which means that the last element that is inserted will
be the first element to be removed from the stack.
● When a stack is completely full, it is said to be Stack is Overflow and if stack is
completely empty, it is said to be Stack is Underflow.

REPRESENTATION & IMPLEMENTATION STACK:


Stacks can be implemented using either arrays or linked lists.

→ARRAY REPRESENTATION OF STACKS:

The stacks can be represented using array .Stack contains an ordered collection of elements.an
array is used to store ordered list of elements .hence it would be very easy to manage a stack if we
represent it using 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.

The drawback of this representation is we are required to declare the size of the array before
using it in a program, means the size of the array is fixed

The variable top indicates the current top of the stack and it moves up and down depending on
whether new items are added to the stack (or) existing item is removed.

1
Example1:

Xxx Yyy Zzz

0 1 2 3 4 5 6 7
MAX=8
TOP=2

Example2:

Array Implementation of Stack:

The basic operations performed in a Stack:


1. Push(x) - add element x at the top of the stack
2. Pop( ) - remove top element from the stack
3. peek() - get top element of the stack without removing it

PUSH operation:

1. The push operation is used to insert an element into the stack. The new element is added at the
topmost position of the stack.
2. Before inserting the value, we must first Check if the stack is full or not.
3. If the stack is full, then print error of overflow and exit the program.
4. If the stack is not full, then increment the top and add the element at top location.

2
Algorithm for PUSH:

POP operation:

1. The pop operation is used to delete the topmost element from the stack. However, before
deleting the value, we must first Check if the stack is empty or not.
2. If the stack is empty, then print error of underflow and exit the program.
3. If the stack is not empty, then print the element at the top and decrement the top.

Page | 3
Algorithm for POP operation:

Peek operation:
Peek is an operation that returns the value of the topmost element of the stack without deleting it from the
stack. The algorithm for Peek operation is given in below.
However, the Peek operation first checks if the stack is empty,i.e., if TOP = NULL, then an appropriate
message is printed, else the value is returned.
Algorithm for PEEK operation

Display:

It is used to display all the elements from the stack


Algorithm for stack display:

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'.

→LINKED REPRESENTATION OF STACKS


We have seen how a stack is created using an array. This technique of creating a stack is easy,
but the drawback is that the array must be declared to have some fixed size. But if the array size
cannot be determined in advance, then the other alternative, i.e., linked representation, is used.
In a linked stack, every node has two parts—one that stores data and another that stores the
address of the next node. The START pointer of the linked list is used as TOP. All insertions and
deletions are done at the node pointed by TOP. If TOP = NULL, then it indicates that the stack is

Page | 4
empty. The linked representation of a stack is shown in Fig. 7.13.

OPERATIONS ON A LINKED STACK


A linked stack supports all the three stack operations, that is, push, pop, and peek.
Push Operation
The push operation is used to insert an element into the stack. The new element is added at the
topmost position of the stack. Consider the linked stack shown in Fig. 7.14.

Page | 5
To insert an element with value 9, we first check if TOP=NULL. If this is the case, then we
allocate memory for a new node, store the value in its DATA part and NULL in its NEXT part. The
new node will then be called TOP. However, if TOP!=NULL, then we insert the new node at the
beginning of the linked stack and name this new node as TOP. Thus, the updated stack becomes as
shown in Fig. 7.15.

Figure 7.16 shows the algorithm to push an element into a linked stack. In Step 1, memory is
allocated for the new node. In Step 2, the DATA part of the new node is initialized with the value to
be stored in the node. In Step 3, we check if the new node is the first node of the linked list. This is
done by checking if TOP = NULL. In case the IF statement evaluates to true, then NULL is stored in
the NEXT part of the node and the new node is called TOP. However, if the new node is not the first
node in the list, then it is added before the first node of the list (that is, the TOP node) and termed as
TOP.

Page | 6
Pop Operation
The pop operation is used to delete the topmost element from a stack. However, before
deleting the value, we must first check if TOP=NULL, because if this is the case, then it means that
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. Consider the stack shown in Fig.
7.17.

In case TOP!=NULL, then we will delete the node pointed by TOP, and make TOP point to the
second element of the linked stack. Thus, the updated stack becomes as shown in Fig. 7.18.

Figure 7.19 shows the algorithm to delete an element from a stack. In Step 1, we first check for
the UNDERFLOW condition. In Step 2, we use a pointer PTR that points to TOP. In Step 3, TOP is
made to point to the next node in sequence. In Step 4, the memory occupied by PTR is given back to
the free pool.

Page | 7
→Applications of stack:

1. Reversing a list

2. Recursion

3. Evaluation of postfix expression

4. Conversion of infix expression to postfix expression

5. Conversion of infix expression to prefix expression

→Reversing the list:

The stack usually works by inserting a new element into top of the stack and deleting the
element from the top of the stack.

The elements of stack are displayed from top to bottom of stack, i.e. which displays the
element reverse order based on insertion.

To understand this, imagine a pile of books usually, we pick up the topmost book from the
pile. The elements in the list are displayed in reverse order.

Algorithm for displaying the elements using arrays:

display ()
begin
Initialize i
if top=-1
write stack is empty
otherwise
for i=top to 0
print stack[i]
end of if
end of display

Page | 8
→Evaluation of Arithmetic Expressions:
● An expression is defined as the combination of operands (variables, constants) and
operatorsarranged as per the syntax of the language.
● An expression can be represented using three different notations. They are infix,
postfix andprefix notations:
Prefix: An arithmetic expression in which we fix (place) the arithmetic operator before (pre)
its twooperands. The prefix notation is called as polish notation. Example: + A B
Infix: An arithmetic expression in which we fix (place) the arithmetic operator in
between the twooperands. Example: A + B
Postfix: An arithmetic expression in which we fix (place) the arithmetic operator after (post) its
twooperands. The postfix notation is called as suffix notation OR reverse polish notation.
Example: A B +

Operator Precedence: When an expression consist different level of operators we follow it.
We consider five binary operations: +, -, *, / and ^ (exponentiation). For these binary
operations, thefollowing in the order of precedence (highest to lowest): ^ , * , /, +,-

Operator Associativity: When an expression consist more than one same level precedence
operators we follow it.

Basically we have Left to Right associativity and Right to Left Associativity. Most of the
operators are follows Left to Right but some of the operators are follow Right to left
Associativity like Unary (+/-), ++/-- , Logical negation (!), Pointer and address (*,&),
Conditional Operators and Assignment operators(=,+=,-=,*=,/=,%=).

Example: x=a/b-c+d*e-a*c

Let a = 4, b = c = 2, d = e = 3 then the value of x is found as

= ((4 / 2) – 2) + (3 * 3) – (4 * 2) =0+9–8 =1

Page | 9
→Algorithm for Transforming Infix to Postfix

Page | 10
EXAMPLE:

Convert the following infix expression to postfix expression

A*B/(C-D)+E*(F-G)

First we push “(“onto STACK, and then we add “)” to the end of Q to obtain:

A * B / ( C - D ) + E * ( F - G ) )
(1) (2) (3) (4) (5) (6) (7) (8) (9) (10) (11) (12) (13) (14) (15) (16) (17) (18)

Input (Symbol Scanned) stack operations postfix notation

(1) A ( A

(2) * (* A

(3) B (* AB

(4) / (/ AB*

(5) ( (/( AB*

(6) C (/( AB*C

(7) - ( / (- AB*C

(8) D ( / (- AB*CD

(9) ) (/ AB*CD-

(10) + (+ AB*CD-/

(11) E (+ AB*CD-/E

(12) * (+* AB*CD-/E

(13) ( (+*( AB*CD-/EF

(14) F (+*( AB*CD-/EF

(15) - (+*(- AB*CD-/EF

(16) G (+*(- AB*CD-/EFG


Page | 11
(17) ) (+* AB*CD-/EFG-

(18) ) EMPTY AB*CD-/EFG-*+

The postfix for infix expression A*B/(C-D) +E*(F-G) is AB*CD-/EFG-*+

→Convert the following infix expression to postfix expression

A+ (B*C-(D/E^F)*G)*H

First we push “(“onto STACK, and then we add “)” to the end of Q to obtain:

The postfix for infix expression A+ (B*C-(D/E^F)*G)*H is ABC*DEF^/G*-H*+

Page | 12
→Conversion of an Infix Expression into a Prefix Expression:-

Algorithm to convert an infix expression into prefix expression

Example

For example, given an infix expression (A – B/C) * (A / K – L)


Step 1: Reverse the infix string. Note that while reversing the string you must interchange left
and right parentheses.
(L – K / A) * (C / B – A)
Step 2: Obtain the corresponding postfix expression of the infix expression obtained as
a result of Step 1.

First we push “(“onto STACK, and then we add “)” to the end of Q to obtain:

( L – K / A ) * ( C / B – A ) )

Input(symbol scanned) Stack operations Notation

(1) ( ( (

(2) L (( L

(3) - ((- L

(4) K ((- LK

(5) / ((-/ LK

(6) A ((-/ LKA

(7) ) ( LKA/-

(8) * (* LKA/-

Page | 13
(9) ( (*( LKA/-

(10) C (*( LKA/-C

(11) / (*(/ LKA/-C

(12) B (*(/ LKA/-CB

(13) - (*(- LKA/-CB/

(14) A (*(- LKA/-CB/A

(15) ) (* LKA/-CB/A-

(16) ) LKA/-CB/A-*

Therefore the expression we get after step2 is LKA/–CB/A–*

Step 3: Reverse the postfix expression to get the prefix expression

Therefore, the prefix expression is * – A / B C – /A K L

Page | 14
→Evaluation of arithmetic expression:-

The stacks are used in evaluation of arithmetic expression. The stacks will evaluate the infix
expression by converting into postfix expression. Then it evaluates the postfix expression.

Evaluation of a Postfix Expression

POSTFIXEVAL (P)

This algorithm finds the VALUE of an arithmetic expression P written in postfix notation.

1. Add a right parenthesis “)” at the end of P [this acts as a sentinel]

2 Scan P from left to right and repeat steps 3 and 4 for each element of P until the sentinel
“)” is encountered

3. If an operand is encountered put it on STACK

4. If an operator is encountered Then:

Remove the top two elements of a STACK, where A is the top element and B is

the next-to-top element

Evaluate B operator A

Place the result of (b) back on STACK.

[End of If structure]

[End of Step 2 loop]

5. Set VALUE equal to the top element on stack

6. Exit

Page | 15
Example 1: Evaluate the Postfix Expression 4 5 6 * +

-> add “)” to the end of expression

Input Symbol /
Symbol Operation Stack Calculation
Scanned

4 Push 4

5 Push 4,5

6 Push 4,5,6

* Pop (2 Elements) 4 5*6=30


& Evaluate

Push result(30) 4,30

+ Pop (2 Elements) Empty 4+30=34


& Evaluate

Push result(34) 34

) Empty 34

Result=34

Example 2: Evaluate the following postfix expression

6 , 8 , + , 9, 2, -, /

-> add “)” to the end of expression

P: 6, 8, +, 9, 2, -, /, )

Input Symbol /
Operation Stack Calculation
Symbol Scanned

6 Push 6

8 Push 6,8

Pop (2 Elements)
+ 8+6=14
& Evaluate

Page | 16
Push result(14) 14

9 Push 14,9

2 Push 14,9,2

Pop (2 Elements)
- 14 9-2=7
& Evaluate

Push result(7) 14,7

Pop (2 Elements)
/ 14/7=2
& Evaluate

Push result(2) 2

) Empty 2

VALUE=2.

For the above example the result is 2.

Page | 17
EXAMPLE 2:

Evaluate the following postfix expression

5, 6, 2, +, *, 12, 4, /, -

add “)” to the end of expression

P: 5, 6, 2, +, *, 12, 4, /, - ,)

Symbol Scanned Operation STACK Calculation

5 Push 5

6 Push 5,6

2 Push 5,6,2

+ Pop (2 Elements) & 5 6+2=8


Evaluate

Push result(8) 5,8

* Pop (2 Elements) & 5*8=40


Evaluate

Push result(40) 40

12 Push 40,12

4 Push 40,12,4

/ Pop (2 Elements) & 40 12/4=3


Evaluate

Push result(3) 40,3

- Pop (2 Elements) & 40-3=37


Evaluate

Push result(37) 37

) 37

Result= 37

Page | 18

You might also like