0% found this document useful (0 votes)
14 views63 pages

DS Unit 2 Array - Stack

Uploaded by

Hiragar Harshil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
14 views63 pages

DS Unit 2 Array - Stack

Uploaded by

Hiragar Harshil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 63

Unit-2 Linear Data Structure-Array & Stack

❖ Outline:
• Definition of Array
• Types of Array
• Representation of Array
• Application of Array
• Stack Definition and Concept
• Operations on Stack (push,pop,peep,change)
• Application of Stack
1.Expression Conversion
(Infix, Postfix(Reverse Polish), Prefix(Polish))
1. 2.Expression Evaluation.
• Tower of Hanoi. NLJIET 1
Unit-2 Linear Data Structure-Array
❖ What is an Array?
• An array is a data structure that contains a group of elements.
• Typically these elements are all of the same data type, such as an integer or string.
• Arrays are commonly used in computer programs to organize data so that a related set
of values can be easily sorted or searched.
• An array is a collection of data items, all of the same type, accessed using a common
name.

❖ Types of Array:
1. One Dimensional
2. Two Dimensional
3. Multi Dimensional
NLJIET 2
Unit-2 Linear Data Structure-Array
❖ Types of Array:
1. One Dimensional Array:
• An array which store its elements into a single row is called one dimensional array.
• Syntax for Declare an Array
datatype ArrayName[Arraysize];
For Example: Float Mark[5];
• Here, we declared an array, mark, of floating-point type. And its size is 5. Meaning, it can
hold 5 floating-point values.

NLJIET 3
Unit-2 Linear Data Structure-Array
1. One Dimensional Array:
❑ How to Access Array Elements?
• You can access elements of an array by indices.
• Suppose you declared an array mark as above. The first element is mark[0], the second
element is mark[1] and so on.
• Arrays have 0 as the first index, not 1. In our example, mark[0] is the first element.
• If the size of an array is n, to access the last element, the n-1 index is used. In this
example, mark[4].
• Suppose the starting address of mark[0] is 2120. Then, the address of the mark[1] will be
2124. Similarly, the address of mark[2] will be 2128 and so on. This is because the size of
a float is 4 bytes.

NLJIET 4
Unit-2 Linear Data Structure-Array
1. One Dimensional Array:
❑ How to Initialize an Array?
• It is possible to initialize an array during declaration. For example,
int mark[5] = {19, 10, 8, 17, 9};

• Input and Output Array Element


• Here's how you can take input from the user and store it in an array element.
scanf("%d", &mark[2]); // take input and store it in the 3rd element
scanf("%d", &mark[i-1]); // take input and store it in the ith element

NLJIET 5
Unit-2 Linear Data Structure-Array
1. One Dimensional Array:
• Here's how you can print an individual element of an array.
printf("%d", mark[0]); // print the first element of the array
printf("%d", mark[2]); // print the third element of the array
printf("%d", mark[i-1]); // print ith element of the array

NLJIET 6
Unit-2 Linear Data Structure-Array
1. One Dimensional Array:
❑ Example: Array Input/output
#include<stdio.h>
void main()
{
int a[4];
int i, j;
OUTPUT:
printf("Enter array element:");
Enter array element:1
for(i = 0; i < 4; i++) 5
{ 2
scanf("%d", &a[i]); //Run time array initialization 3
}
printf(“Array elements are:"); Array Elements are:1
5
for(j = 0; j < 4; j++)
2
{ 3
printf("%d\n", a[j]);
}
NLJIET 7
}
Unit-2 Linear Data Structure-Array
❖ Types of Array:
2. Two Dimensional Array:
• C language supports multidimensional arrays also.
• The simplest form of a multidimensional array is the two-dimensional array.
• An array of arrays is known as 2D array.
• The two dimensional (2D) array in C programming is also known as matrix.
• A matrix can be represented as a table of rows and columns.
• Two-dimensional arrays are declared as follows,
data-type array-name[row-size][column-size] ;
For Example, float x[3][4];
• Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the
array as a table with 3 rows and each row has 4 columns.
NLJIET 8
Unit-2 Linear Data Structure-Array
❖ Types of Array:
2. Two Dimensional Array:

• Similarly, you can declare a three-dimensional (3d) array. For example,


float y[2][4][3];
• Here, the array y can hold 24 elements.

NLJIET 9
Unit-2 Linear Data Structure-Array
2. Two Dimensional Array:
❑ How to initialize 2D Array?
• Different ways to initialize two-dimensional array
i=0 j=0 : a[0][0]
int c[2][3] = {{1, 3, 0}, {-1, 5, 9}}; j=1 : a[0][1]
int c[][3] = {{1, 3, 0}, {-1, 5, 9}}; j=2 : a[[0][2]
j=3 : a[0][3]
int c[2][3] = {1, 3, 0, -1, 5, 9};
• Runtime initialization of a two dimensional Array i=1 j=0 :a[1][0]
j=1 :a[1][1]
Suppose array size is a[3][4]
j=2 :a[1][2]
for(i = 0; i < 3;i++) j=3 :a[1][3]
{
i=2 j=0 :a[2][0]
for(j = 0; j < 4; j++) j=1 :a[2][1]
{ j=2 :a[2][2]
j=3 :a[2][3]
scanf("%d", &a[i][j]); i=3 condition false
}
NLJIET 10
}
Unit-2 Linear Data Structure-Array
2. Two Dimensional Array:
❑ Example: 2D Array Input/output
#include<stdio.h> 0 1 2 3
void main()
{
int arr[3][4];
int i, j, k;
0 5 10 15 20
printf("Enter array element");
for(i = 0; i < 3;i++)
{
for(j = 0; j < 4; j++) 1 25 30 35 40
{
scanf("%d", &arr[i][j]);
}
} 2 45 50 55 60
for(i = 0; i < 3; i++)
{
for(j = 0; j < 4; j++)
{ printf("%d", arr[i][j]);
}
}
}
NLJIET 11
Unit-2 Linear Data Structure-Array
❖ Array Representation:
• The elements of a Two dimensional array can be arranged in two ways.
1. Row major Representation
2. Column major Representation
1.Row major Representation:
• If the elements are stored in row wise manner then it is called row major representation.
• If we want to store element 10,20,30,40,50,60,70,80 and if size of array is a[3][4] then,
0 1 2 3

0
10 20 30 40
1 50 60 70 80
2
NLJIET 12
Unit-2 Linear Data Structure-Array
❖ Array Representation:
2.Column major Representation:
• If the elements are stored in column wise manner then it is called Column major
representation.
• If we want to store element 10,20,30,40,50,60,70,80 and if size of array is a[3][4] then,
0 1 2 3

0
10 40 70

1
20 50 80

2
30 60

NLJIET 13
Unit-2 Linear Data Structure-Array
❖ Address calculation of Array Elements :
• You can calculate the address of any element which is stored in an array.
• To calculate the address of any element you must know,
1.Base Address(Address of first element(which is at index 0).
2.Data Types of Array(int(2bytes),Float(4 bytes)).
3. Size of Array.
4.Representation of array(Row major or Column Major)
5.index of element for which you want to find address.
6.Formula.

NLJIET 14
Unit-2 Linear Data Structure-Array
❖ Address calculation of Array Elements :
❑ Formula for Calculating Address:
Row Major System:
The address of a location in Row Major System is calculated using the following formula:
Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
Column Major System:
The address of a location in Column Major System is calculated using the following formula:
Address of A [ I ][ J ] Column Major Wise = B + W * [( I – Lr ) + M * ( J – Lc )]
Where,
B = Base address(Address of First Element)
I = Row subscript of element whose address is to be found
J = Column subscript of element whose address is to be found
W = Storage Size of one element stored in the array (in byte)(Int=2 byte,Float=4 byte)
Lr = Lower limit of row/start row index of matrix, if not given assume 0 (zero)
Lc = Lower limit of column/start column index of matrix, if not given assume 0 (zero)
M = Number of row of the given matrix
N = Number of column of the given matrix
NLJIET 15
Unit-2 Linear Data Structure-Array
❖ Address calculation of Array Elements :
❑Example 1:Consider an integer array int a[3][4].if the base address is 1050,find the
address of the element a[2][2] with row major and column major representation of
array.
Row Major System:
The address of a location in Row Major System is calculated using the following formula:
Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
B = Base address(Address of First Element)=1050
I = Row subscript of element whose address is to be found=2
J = Column subscript of element whose address is to be found=2
W = Storage Size of one element stored in the array =2 bytes(because datatype is int).
Lr = Lower limit of row/start row index of matrix, if not given assume 0 (zero)=0
Lc = Lower limit of column/start column index of matrix, if not given assume 0 (zero)=0
M = Number of row of the given matrix=3
N = Number of column of the given matrix=4
NLJIET 16
Unit-2 Linear Data Structure-Array
❖ Address calculation of Array Elements :
❑Example 1:Consider an integer array int a[3][4].if the base address is 1050,find the
address of the element a[2][2] with row major and column major representation of
array.
❑ Row Major System:
The address of a location in Row Major System is calculated using the following formula:
Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
A [ 2 ][ 2 ] = 1050 + 2 * [ 4 * ( 2 – 0 ) + ( 2 – 0) ]
= 1070 0 1 2 3

0 1050 1052 1054 1056


1 1058 1060 1062 1064
2 1066 1068 ?(1070)

NLJIET 17
Unit-2 Linear Data Structure-Array
❖ Address calculation of Array Elements :
❑Example 1:Consider an integer array int a[3][4].if the base address is 1050,find the
address of the element a[2][2] with row major and column major representation of
array.
Column Major System:
The address of a location in Column Major System is calculated using the following formula:
Address of A [ I ][ J ] Column Major Wise = B + W * [( I – Lr ) + M * ( J – Lc )]
A [ 2 ][ 2 ] = 1050 + 2 * [ ( 2 – 0 ) + 3*( 2 – 0) ]
= 1050+16 0 1 2 3
= 1066 0 1050 1056 1062
1 1052 1058 1064
2 1054 1060 ?(1066)

NLJIET 18
Unit-2 Linear Data Structure-Array
❖ Address calculation of Array Elements :
❑Example 2:A 2-D array defined as A[r, c] where 1 ≤ r ≤ 4, 5≤ c ≤ 8, requires 2 bytes of memory for
each element. If the array is stored in Row-major order form, calculate the address of A[3,7]
given the Base address as 2000
Size of Array A[1:4][5:8]
Row Major System:
The address of a location in Row Major System is calculated using the following formula:
Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
B=2000 =2000 + 2[ 4*(3-1) +( 7-5)
5 6 7 8
W=2 byte =2000 + 2*10
I=3 =2000+20 1 2000 20002 2004 2006
J=7 =2020 2 2008 2010 2012 2014
Lr=1
Lc=5 3 2016 2018 ?(2020)
M=4 4
N= 4
NLJIET 19
Unit-2 Linear Data Structure-Array
❖ Address calculation of Array Elements :
❑Example 2:A 2-D array defined as A[r, c] where 1 ≤ r ≤ 4, 5≤ c ≤ 8, requires 2 bytes of memory for
each element. If the array is stored in Row-major order form, calculate the address of A[3,7]
given the Base address as 2000
Size of Array A[1:4][5:8}
Column Major System:
The address of a location in Column Major System is calculated using the following formula:
Address of A [ I ][ J ] Column Major Wise = B + W * [( I – Lr ) + M * ( J – Lc )]
B=2000 =2000 + 2[ (3-1) +4*( 7-5)
5 6 7 8
W=2 byte =2000 + 2*10
I=3 =2000+20 1 2000 2008 2016
J=7 =2020 2 2002 2010 2018
Lr=1
Lc=5 3 2004 2012 ?(2020)
M=4 4 2006 2014
N= 4
NLJIET 20
Unit-2 Linear Data Structure-Array
❖ Address calculation of Array Elements :
❑ Example 3:Given a two dimensional array Z1(2:9, 9:18) stored in column-major order with base
address 100 and size of each element is 4 bytes, find address of the element Z1(4, 12).
Size of Array A[2:9][9:18]
Column Major System:
The address of a location in Column Major System is calculated using the following formula:
Address of A [ I ][ J ] Column Major Wise = B + W * [( I – Lr ) + M * ( J – Lc )]
B=100 =100 + 4[ (4-2) +8*( 12-9) 9 10 11 12 13 14 15 16 17 18
W=4 byte =100 + 4[2+8*3] 2 100 132 164 196

I=4 =100+4*26 3 104 136 168 200

J=12 =100+104 4 108 140 172 ?204

Lr=2 =204 5 112 144 176

Lc=9 6 116 148 180

120 152 184


M=8(9-2+1) 7
124 156 188
N= 10(18-9+1) 8
128 160 192
9
NLJIET 21
Unit-2 Linear Data Structure-Array
❖ Address calculation of Array Elements :
❑ Example 3:Given a two dimensional array Z1(2:9, 9:18) stored in column-major order with base
address 100 and size of each element is 4 bytes, find address of the element Z1(4, 12).
Size of Array A[2:9][9:18]
Row Major System:
The address of a location in Row Major System is calculated using the following formula:
Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
B=100 =100 + 4[ 10(4-2) +( 12-9) 9 10 11 12 13 14 15 16 17 18
W=4 byte =100 + 4[20+3] 2 100 104 108 112 116 120 124 128 132 136

I=4 =100+4*23 3 140 144 148 152 156 160 164 168 172 176

J=12 =100+92 4 180 184 188 ?192

Lr=2 =192 5
Lc=9 6
M=8(9-2+1) 7
N= 10(18-9+1) 8
9
NLJIET 22
Unit-2 Linear Data Structure-Array
❖ Applications of Array:
• Array are used for representing some sequential data structures such as stack and
queues.
• Array are used to represent sparse matrices.
• Array are widely used to implement mathematical vector, matrices and other kind of
tables.
• Array can be used for sorting elements in ascending or descending order.
• It is used in every possible situation where you need to gather similar objects at one
place.
• Arrays are used to implement Search Algorithms.
• Arrays are also used to implement CPU Scheduling Algorithms.

NLJIET 23
sparse matrix and its representation

• Sparse matrices are those matrices that have the majority of their elements equal to
zero.
• In other words, the sparse matrix can be defined as the matrix that has a greater number
of zero elements than the non-zero elements.
• Now, the question arises: we can also use the simple matrix to store the elements, then
why is the sparse matrix required?
• There are the following benefits of using the sparse matrix –

• Storage - We know that a sparse matrix contains lesser non-zero elements than zero, so
less memory can be used to store elements. It evaluates only the non-zero elements.

• Computing time: In the case of searching in sparse matrix, we need to traverse only the
non-zero elements rather than traversing all the sparse matrix elements. It saves
computing time by logically designing a data structure traversing non-zero elements.
NLJIET 24
Representation of sparse matrix

• The non-zero elements in the sparse matrix can be stored using triplets that are rows, columns, and
values.
• There are two ways to represent the sparse matrix that are listed as follows –
Array representation
Linked list representation

Array representation of the sparse matrix


• Representing a sparse matrix by a 2D array leads to the wastage of lots of memory.
• This is because zeroes in the matrix are of no use, so storing zeroes with non-zero elements is
wastage of memory.
• To avoid such wastage, we can store only non-zero elements.
• If we store only non-zero elements, it reduces the traversal time and the storage space.
• In 2D array representation of sparse matrix, there are three fields used that are named as –

NLJIET 25
Row - It is the index of a row where a non-zero element is located in the matrix.
Column - It is the index of the column where a non-zero element is located in the matrix.
Value - It is the value of the non-zero element that is located at the index (row, column).

Example -
Let's understand the array representation of sparse matrix with the help of the example given below
-Consider the sparse matrix –

• In the above figure, we can observe a 5x4 sparse matrix containing 7 non-zero elements and 13
zero elements. The above matrix occupies 5x4 = 20 memory space. Increasing the size of matrix
will increase the wastage space.

NLJIET 26
The tabular representation of the above matrix is given below –

• In the above structure, first column represents the rows, the second column represents the columns, and
the third column represents the non-zero value.
• The first row of the table represents the triplets. The first triplet represents that the value 4 is stored at 0th
row and 1st column. Similarly, the second triplet represents that the value 5 is stored at the 0th row and
3rd column. In a similar manner, all triplets represent the stored location of the non-zero elements in the
matrix.
• The size of the table depends upon the total number of non-zero elements in the given sparse matrix.
Above table occupies 8x3 = 24 memory space which is more than the space occupied by the sparse matrix.
• So, what's the benefit of using the sparse matrix? Consider the case if the matrix is 8*8 and there are only 8
non-zero elements in the matrix, then the space occupied by the sparse matrix would be 8*8 = 64, whereas
the space occupied by the table represented using triplets would be 8*3 = 24.
NLJIET 27
Linked List representation of the sparse matrix

• In a linked list representation, the linked list data structure is used to represent the sparse matrix.
• The advantage of using a linked list to represent the sparse matrix is that the complexity of
inserting or deleting a node in a linked list is lesser than the array.
• Unlike the array representation, a node in the linked list representation consists of four fields.
• The four fields of the linked list are given as follows –

Row - It represents the index of the row where the non-zero element is located.
Column - It represents the index of the column where the non-zero element is located.
Value - It is the value of the non-zero element that is located at the index (row, column).
Next node - It stores the address of the next node.

The node structure of the linked list representation of the sparse matrix is shown in the below image -

NLJIET 28
Example -
Let's understand the linked list representation of sparse matrix with the help of the example given below -
Consider the sparse matrix -

In the above figure, we can observe a 4x4 sparse matrix containing 5 non-zero elements and 11 zero elements.
Above matrix occupies 4x4 = 16 memory space. Increasing the size of matrix will increase the wastage space.
The linked list representation of the above matrix is given below -

In the above figure, the sparse matrix is represented in the linked list form. In the node, the first field represents
the index of the row, the second field represents the index of the column, the third field represents the value,
and the fourth field contains the address of the next node.
In the above figure, the first field of the first node of the linked list contains 0, which means 0th row, the second
field contains 2, which means 2nd column, and the third field contains 1 that is the non-zero element. So, the
first node represents that element 1 is stored at the 0th row-2nd column in the given sparse matrix. In a similar
manner, all of the nodes represent the non-zero elements of the sparse matrix.
NLJIET 29
STACK

NLJIET
Unit-2 Linear Data Structure-Stack
❖ Stack Definition and Concept:
• A linear list which allow insertion and deletion of an element at one end only is called
Stack.
• A Stack is a data structure which is used to store data in a particular order.
• It follows Last In First Out(LIFO) Order.
• The element which is inserted last, that will be come out first.
• There are many real-life examples of a stack.
• Consider an example of plates stacked over one another in the canteen.

NLJIET 31
❖ Operations on Stack:
• There are four operations which we can perform on stack.
1. Push(Insert): Which insert an element at TOP of the stack.
2. Pop(Delete): Which Remove the most recently added elements from the
TOP of the stack.
3. Peep(Search): To find ith element from TOP of the stack.
4. Change(Update):Changes the value of the ith element from the TOP of the stack.

NLJIET 32
Unit-2 Linear Data Structure-Stack
❖ Operations on Stack:
• TOP is a pointer that points to the top element of stack.
• Initially when the Stack is Empty, TOP has a value of “Zero”.
• Each time a new element is inserted in the stack, the pointer is Incremented by “one”.
• The pointer is decremented by “one” each time a deletion is made from the stack

NLJIET 33
Unit-2 Linear Data Structure-Stack
❖ Procedure: PUSH(S,TOP,X)
• This procedure insert an element X to the top of a stack.
• Stack is represented by a vector S Containing N Elements.
• A pointer TOP represents the top element of the stack.
1. [Check for Stack overflow] Stack is Empty, TOP=0
If Top ≥ N N=3
then Write (‘Stack Overflow’)
PUSH(S,TOP,10) ,TOP=1
Return PUSH(S,TOP,15),TOP=2
2.[Increment Top] 30 TOP=3
PUSH(S,TOP,30),TOP=3
Top ← Top + 1 PUSH(S,TOP,40),
TOP=2 15 15
3.[Insert Element] Overflow
S[Top] ← X
TOP=1 10 10 10
4.[Finished]
Return
NLJIET S 34
S S
Unit-2 Linear Data Structure-Stack
❖ Procedure: POP(S,TOP)
• This procedure remove and returns the
top element from a stack.
• Stack is represented by a vector S Containing N Elements.
Stack is FULL, TOP=3,
• A pointer TOP represents the top element of the stack. N=3
1. [Check for underflow on Stack] POP(S,TOP),TOP=3,
If Top = 0 TOP=2
then Write (‘Stack Underflow on Pop’) Return S[2+1]
Exit POP(S,TOP),TOP=2, TOP=3 30
2.[Decrement Pointer] TOP=1
Top ← Top-1 Return S[1+1] 15 TOP=2 15
3. [Return former top element of POP(S,TOP),TOP=1
Stack] TOP=0 10 10 TOP=1 10
Return S[0+1]
Return (S[Top+1])
POP(S,TOP),TOP=0
NLJIET S S 35S
Underflow
Unit-2 Linear Data Structure-Stack
❖ Procedure: PEEP(S,TOP,I)
• This procedure returns the value of ith element from
top of the stack.
• The element is not deleted by this function.
• Stack is represented by a vector S Containing N Elements.
• A pointer TOP represents the top element of the stack.
1. [Check for Stack Underflow] Stack is FULL, TOP=5,
If (Top - I + 1) ≤ 0 N=5 TOP=5 50
then Write (‘Stack Underflow on 40
PEEP(S,TOP,4)= 5 – 4 + 1=2=S[2]=20
Peep’) PEEP(S,TOP,2)= 5 – 2 + 1=4=S[4]=40
30
Exit PEEP(S,TOP,6)= 5 – 6 + 1=0=S[0]=Underflow 20
2.[Return Ith element from top 10
of the stack] NLJIET 36
S
Return (S[Top-I+1])
Unit-2 Linear Data Structure-Stack
❖ Procedure: CHANGE(S,TOP,X,I)
• This procedure changes the value of ith element from the top of
the stack to the value contained in X.
• Stack is represented by a vector S Containing N Elements.
• A pointer TOP represents the top element of the stack
1. [Check for stack underflow]
If (Top - I + 1) ≤ 0 Stack is FULL, TOP=5,
then Write (‘Stack Underflow on Change’) N=5
TOP=5 50 50
Exit
2.[Change the Ith element from top of stack] 40 70
CHANGE(S,TOP,60,4)= 5 – 4 + 1=2=S[2]=60
S[Top - I + 1] ← X 30 30
CHANGE(S,TOP,70,2)= 5 – 2 + 1=4=S[4]=70
3.[Finished] CHANGE(S,TOP,6)= 5 – 6 + 1=0=S[0]=Underflow 20 60
Return 10 10

NLJIET 37
S S
Unit-2 Linear Data Structure-Stack
❖ Application of Stack:
1. Expression Conversion: An expression is a collection of
operators and operands that represents a specific value.
• In above definition, operator is a symbol which performs a particular task like arithmetic
operation.
• Operands are the values on which the operators can perform the task.
• For Example, A + B * C
• An arithmetic expression can be written in three different but equivalent notations, i.e.,
without changing the essence or output of an expression.
• These notations are −
1. Infix Notation
2. Prefix (Polish) Notation
NLJIET 38
3. Postfix (Reverse-Polish) Notation
Unit-2 Linear Data Structure-Stack
❖ Expression Conversion:
1. Infix Notation: We write expression in infix notation, e.g. a + b,
where operators are used in-between operands.
2. 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.
3. Postfix Notation: This notation style is known as Reversed Polish Notation(RPN). In this
notation style, the operator is post fixed to the operands i.e., the operator is written after the
operands. For example, ab+. This is equivalent to its infix notation a + b.
Infix =a+b
Prefix = +ab
Postfix = ab+
NLJIET 39
Unit-2 Linear Data Structure-Stack
❖ Expression Conversion:
❑ Precedence and Associativity:
• When an operand is in between two different operators, which operator will take the operand
first, is decided by the precedence of an operator over others. For example −

• As multiplication operation has precedence over addition, b * c will be evaluated first.


• Associativity describes the rule where operators with the same precedence appear in an
expression.
• For example, in expression a + b − c, both + and – have the same precedence, then which part
of the expression will be evaluated first, is determined by associativity of those operators.
• Here, both + and − are left associative, so the expression will be evaluated as (a + b) − c.

NLJIET 40
Unit-2 Linear Data Structure-Stack
❖ Expression Conversion:
❑ Precedence and Associativity:
• Precedence and associativity determines the order of evaluation of an expression. Following is
an operator precedence and associativity table (highest to lowest) −
Symbol Precedence Rank Associativity

+,- 1 (Lowest) -1 Left to Right

*,/ 2 -1 Left to Right

^,$,↑ 3 -1 Right to Left

() 4 - -

A,B,C, …(Variables) 5 (Highest) 1 -

# 0 - -
NLJIET 41
Unit-2 Linear Data Structure-Stack
❖ Expression Conversion:
❑ Infix to postfix conversion: There are two algorithms for that.
1. UNPARENTHESIZED_SUFFIX(Without Bracket).
e.g. a + b * c - d / e

2. REVPOL(With Bracket)
e.g. a * (b + c) - d

NLJIET 42
Unit-2 Linear Data Structure-Stack
❖ Expression Conversion:
1. Algorithm UNPARENTHESIZED_SUFFIX:
This algorithm converts the string INFIX to its reverse Polish string equivalent(POLISH).
INFIX: Input string INFIX representing an infix expression whose single character symbols have
precedence values and ranks as given in Table.
S: vector S representing a stack.
NEXTCHAR: String function NEXTCHAR which, when invoked, returns the next character of the
input string.
RANK: RANK contains the value of each head of the reverse Polish string.
NEXT: NEXT contains the symbol being examined.

NLJIET 43
Unit-2 Linear Data Structure-Stack
❖ Expression Conversion:
Algorithm UNPARENTHESIZED_SUFFIX:
TEMP:TEMP is a temporary variable which contains the unstacked element.
POLISH: which contain final output string(postfix form)
We assume that the given input string is padded on the right with the special symbol “#”.

NLJIET 44
Unit-2 Linear Data Structure-Stack
❖ Expression Conversion: Algorithm UNPARENTHESIZED_SUFFIX:
1. [Initialize the stack] 6. [Push current symbol onto stack and obtain next input symbol]
Top ← 1 Call Push (S, Top, NEXT)
S[Top] ← ‘#’ NEXT ← NEXTCHAR (INFIX)

2.[Initialize output string and rank count] 7.[Remove remaining elements from stack]
POLISH ← ‘’ Repeat while S[Top] ≠ ‘#’
RANK ← 0 TEMP ← Pop (S, Top)
POLISH ← POLISH O TEMP
3. [Get first input symbol] RANK ← RANK + r(TEMP)
NEXT ← NEXTCHAR(INFIX) If RANK < 1
then Write (‘INVALID’)
4.[Translate the infix expression] Exit
Repeat thru step 6 while NEXT ≠ ‘#’
8. [Is the expression valid?]
5. [Remove symbols with greater or equal precedence from stack] If RANK = 1
Repeat while f(NEXT) ≤ f(S[Top]) then Write (‘VALID’)
TEMP ← Pop(S, Top) (this copies the stack contents into TEMP) Else Write (‘INVALID’)
POLISH ← POLISH O TEMP Exit
RANK ← RANK + r(TEMP)
If RANK < 1
then Write (‘INVALID’)
Exit NLJIET 45
Unit-2 Linear Data Structure-Stack
❖ Example:
A+B*C–D
INFIX: A + B * C – D #
Input Content Reverse Polish Rank
Symbol of Stack Expression(POLISH)
(NEXT)
# 0
1.[Initialize the stack]
Top ← 1 A
S[Top] ← ‘#’
2.[Initialize output string
and rank count]
POLISH ← ‘’
RANK ← 0
3. [Get first input symbol]
NEXT ← NEXTCHAR(INFIX)

NLJIET 46
Unit-2 Linear Data Structure-Stack
❖ Example:
A+B*C–D Input Content Reverse Polish Rank
INFIX: A + B * C – D # Symbol of Stack Expression(POLISH)
(NEXT)
4.[Translate the infix expression]
# 0
Repeat thru step 6 while NEXT ≠
‘#’ A (3≤0) #A 0
5.[Remove symbols with greater
or equal precedence from stack] + (1≤3) #+ A 1
Repeat while f(NEXT) ≤ f(S[Top]) (1≤0)
TEMP ← Pop(S, Top) (this copies
the stack contents into TEMP)
B (3≤1) #+B A 1
POLISH ← POLISH O TEMP * (2≤3) #+* AB 2
RANK ← RANK + r(TEMP) (2≤1)
If RANK < 1
then Write (‘INVALID’) C (3≤2) #+*C AB 2
Exit
6.[Push current symbol onto
- (1≤3) #- ABC*+ 1
stack and obtain next input (1≤2)
symbol] (1≤1)
Call Push (S, Top, NEXT)
NEXT ← NEXTCHAR (INFIX)
D(3≤1) #-D ABC*+
NLJIET 47
#
Unit-2 Linear Data Structure-Stack
❖ Example:
A+B*C–D Input Conte Reverse Polish Rank
INFIX: A + B * C – D # Symbol nt of Expression(POLISH)
(NEXT) Stack
7.[Remove remaining # 0
elements from stack]
Repeat while S[Top] ≠ ‘#’ A (3≤0) #A 0
TEMP ← Pop (S, Top) + (1≤3) #+ A 1
POLISH ← POLISH O TEMP (1≤0)
RANK ← RANK + r(TEMP) B (3≤1) #+B A 1
If RANK < 1
then Write (‘INVALID’) * (2≤3) #+* AB 2
Exit (2≤1)
8. [Is the expression valid?] C (3≤2) #+*C AB 2
If RANK = 1 - (1≤3) #- ABC*+ 1
then Write (‘VALID’) (1≤2)
Else Write (1≤1)
(‘INVALID’) Exit
D (3≤1) #-D ABC*+ 1
NLJIET 48
# # ABC*+D- 1
Unit-2 Linear Data Structure-Stack
❖ Expression Conversion:
2. Algorithm REVPOL:
• This algorithm converts INFIX into reverse polish and places the result into POLISH.
• Given an input string INFIX containing an infix expression which has been padded on the right
with ‘)’.
• All Symbol have precedence value given in table.
• Stack is represented by vector S, TOP denotes the top of the stack, Algorithm PUSH and POP
are used for stack manipulation.
• Function NEXTCHAR returns the next symbol from given input string.
• The integer variable RANK contains the rank of Expression.
• The string variable TEMP is used for temporary storage purpose.

NLJIET 49
Unit-2 Linear Data Structure-Stack
❖ Expression Conversion:
2. Algorithm REVPOL:

NLJIET 50
Unit-2 Linear Data Structure-Stack
2. Algorithm REVPOL:
1. [Initialize stack] 4. [Translate the infix expression]
Top ← 1 Repeat thru step 7 while NEXT ≠ ‘’
S[Top] ← ‘(‘ 5. [Remove symbols with greater
precedence from stack]
2.[Initialize output string and rank
If Top < 1 8. [Is the expression valid?]
count] then Write (‘INVALID’)
POLISH ← ‘’ If Top ≠ 0 or RANK ≠ 1
Exit then Write (‘INVALID’)
RANK ← 0 Repeat while f(NEXT) < g(S[TOP])
3. [Get first input symbol] else Write (‘VALID’)
TEMP ← Pop (S, Top)
NEXT ← NEXTCHAR (INFIX) POLISH ← POLISH O TEMP Exit
RANK ← RANK + r(TEMP)
If RANK < 1
then Write (‘INVALID’)
Exit
6. [Are there matching parentheses?]
If f(NEXT) ≠ g(S[Top])
then Call Push (S, Top, NEXT)
else Pop (S, Top)
7. [Get next input symbol]
NEXT ← NEXTCHAR (INFIX) NLJIET 51
Unit-2 Linear Data Structure-Stack
❖ Example:

A * (B + C ) – D Input Content Reverse Polish Rank


INFIX: A * (B + C) – D ) Symbol of Stack Expression(POLISH)
(NEXT)
1. [Initialize stack] ( 0
Top ← 1
S[Top] ← ‘(‘ A
2.[Initialize output string
and rank count]
POLISH ← ‘’
RANK ← 0
3.[Get first input symbol]
NEXT ← NEXTCHAR (INFIX)

NLJIET 52
Unit-2 Linear Data Structure-Stack
Input Content Reverse Polish Rank
Symbol of Stack Expression(POLISH)
❖ Example:
(NEXT)
A * (B + C ) – D
( 0
INFIX: A * (B + C) – D )
A (7<0) (A
4. [Translate the infix expression]
Repeat thru step 7 while NEXT ≠ ‘’ * (3<8) (* A 1
5.[Remove symbols with greater (3<0)
precedence from stack]
( (9<4) (*( A 1
If Top < 1
then Write (‘INVALID’) B (7<0) (*(B A 1
Exit
Repeat while f(NEXT) < g(S[TOP]) + (1<8) (*(+ AB 2
TEMP ← Pop (S, Top) (1<0)
POLISH ← POLISH O TEMP
C (7<2) (*(+C AB 2
RANK ← RANK + r(TEMP)
If RANK < 1 ) (0<8) (* ABC+ 2
then Write (‘INVALID’) (0<2)
Exit (0<0)
6. [Are there matching
parentheses?] - (1<4) (- ABC+* 1
If f(NEXT) ≠ g(S[Top]) (1<0)
then Call Push (S, Top, NEXT) D (7<2) (-D ABC+* 1
else Pop (S, Top)
7.[Get next input symbol] ) (0<8) ABC+ *D- 1
NEXT ← NEXTCHAR (INFIX) (0<2)
(0<0)
NLJIET 53
2. Expression Evaluation:
❖ Algorithm Evaluate_Postfix
• Given an input string POSTFIX represent postfix expression.
• This algorithm evaluates postfix expression and put the result into variable
Answer.
• Stack is represent by vector S, TOP denotes the top of the stack, Algorithm PUSH
and POP are used for stack manipulation.
• Function NEXTCHAR returns the next symbol from given input string.
• OP1,OP2 and TEMP are used for temporary storage purpose.
• PERFORM_OPERATION is a function which perform required operation on OP1
and OP2.

NLJIET 54
2. Expression Evaluation:
❖ Algorithm Evaluate_Postfix
1. [ Initialize Stack ]
Top ← 0
Answer  0
2.[ Evaluate the postfix expression ]
Repeat until last character
TEMP NEXTCHAR (POSTFIX)
If TEMP is OPERAND
Then PUSH(S,TOP,TEMP)
Else
OP2  POP(S,TOP)
OP1  POP(S,TOP)
Answer  PERFORM_OPERATION(OP1,OP2,TEMP)
PUSH(S, TOP, Answer)
3. [Return Answer from Stack]
Return (POP(S,TOP))
NLJIET 55
2. Expression Evaluation:
❖ Algorithm Evaluate_Postfix Example
POSTFIX: 9 3 4 * 8 + 4 / -
TEMP OP1 OP2 Answer Stack
9 9
3 9,3
4 9,3,4
* 3 4 12 9,12
8 9,12,8
+ 12 8 20 9,20
4 9,20,4
/ 20 4 5 9,5
- 9 5 4 4
NLJIET 56
2. Expression Evaluation:
❖ Algorithm Evaluate_Postfix Example

POSTFIX: 5 4 6 + * 4 9 3 / + *
TEMP OP1 OP2 Answer Stack
5 5
4 5,4
6 5,4,6
+ 4 6 10 5,10
* 5 10 50 50
4 50,4
9 50,4,9
3 50,4,9,3

/ 9 3 3 50,4,3
+ 4 3 7 50,7
* 50 7 350 350
NLJIET 57
2. Expression Evaluation:
❖ Algorithm Evaluate_Prefix
• Given an input string PREFIX represent prefix expression.
• This algorithm evaluates prefix expression and put the result into variable
Answer.
• Stack is represent by vector S, TOP denotes the top of the stack, Algorithm PUSH
and POP are used for stack manipulation.
• Function NEXTCHAR returns the next symbol from given input string.
• OP1,OP2 and TEMP are used for temporary storage purpose.
• PERFORM_OPERATION is a function which perform required operation on OP1
and OP2.

NLJIET 58
2. Expression Evaluation:
❖ Algorithm Evaluate_Prefix
1. [ Initialize Stack ]
Top ← 0
Answer  0
2.[ Evaluate the prefix expression ]
Repeat from last character up to First
TEMP NEXTCHAR (PREFIX)
If TEMP is OPERAND
Then PUSH(S,TOP,TEMP)
Else
OP1  POP(S,TOP)
OP2 POP(S,TOP)
Answer  PERFORM_OPERATION(OP1,OP2,TEMP)
PUSH(S, TOP, Answer)
3. [Return Answer from Stack]
Return (POP(S,TOP))
NLJIET 59
❖Example 1:Prefix Evaluation
PREFIX: - 9 / + * 3 4 8 4
TEMP OP1 OP2 Answer Stack
4 4
8 4,8
4 4,8,4
3 4,8,4,3
* 3 4 12 4,8,12
+ 12 8 20 4,20
/ 20 4 5 5
9 5,9
- 9 5 4 4
NLJIET 60
❖ Example 2:Prefix Evaluation
PREFIX: + * A B – C + C * B A (A= 4, B=8,C=12)
+ * 4 8 – 12 + 12 * 8 4
TEMP OP1 OP2 Answer Stack
4 4
8 4,8
* 8 4 32 32
12 32,12
+ 12 32 44 44
12 44,12
- 12 32 -20 -20
8 -20,8
4 -20,8,4
* 4 8 32 -20,32
+ 32 -20 12 12
NLJIET 61
Unit-2 Linear Data Structure-Stack
❖ Tower of Hanoi:
▪ The Tower of Hanoi is a mathematical game or Puzzle.
▪ It consists of three rods and a number of disks of different sizes,
which can slide onto any rod.
▪ The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the
smallest at the top, thus making a conical shape.
▪ The objective of the puzzle is to move the entire stack to another rod, obeying the following simple
rules:
1. Only one disk can be moved at a time.
2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another
stack or on an empty rod.
3. No larger disk may be placed on top of a smaller disk.
▪ With 3 disks, the puzzle can be solved in 7 moves. The minimal number of moves required to solve a
Tower of Hanoi puzzle is 2n − 1, where n is the number of disks.
NLJIET 62
Unit-2 Linear Data Structure-Stack
❖Tower of Hanoi:

NLJIET 63

You might also like