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

Unit4 OOP&DS

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

Object Oriented Programming & Data Structure

Unit 4.Data Structure


What is Data Structure?

The data structure name indicates itself that organizing the data in memory.

There are many ways of organizing the data in the memory as we have already seen one of the
data structures, i.e., array in C language.

Array is a collection of memory elements in which data is stored sequentially, i.e., one after
another.

In other words, we can say that array stores the elements in a continuous manner.

There are also other ways to organize the data in memory.

Let's see the different types of data structures.

Types of Data Structures

Page 1
Object Oriented Programming & Data Structure

There are two types of data structures:

 Primitive data structure


 Non-primitive data structure

Primitive Data structure

The primitive data structures are primitive data types. The int, char, float, double, and pointer
are the primitive data structures that can hold a single value.

Non-Primitive Data structure

The non-primitive data structure is divided into two types:


1. Linear data structure 2. Non-linear data structure

Linear Data Structure

The arrangement of data in a sequential manner is known as a linear data structure. Ex. Arrays,
Linked list, Stacks, and Queues.

In these data structures, one element is connected to only one another element in a linear form.

Data structures can also be classified as:

 Static data structure: It is a type of data structure where the size is allocated at the
compile time. Therefore, the maximum size is fixed.
 Dynamic data structure: It is a type of data structure where the size is allocated at the
run time. Therefore, the maximum size is flexible.

Major Operations
The major or the common operations that can be performed on the data structures are:

 Searching: We can search for any element in a data structure.


 Sorting: We can sort the elements of a data structure either in an ascending or
descending order.
 Insertion: We can also insert the new element in a data structure.
 Updation: We can also update the element, i.e., we can replace the element with another
element.
 Deletion: We can also perform the delete operation to remove the element from the data
structure.

Page 2
Object Oriented Programming & Data Structure

Advantages of Data structures

The following are the advantages of a data structure:

 Efficiency: If the choice of a data structure for implementing a particular ADT is proper,
it makes the program very efficient in terms of time and space.
 Reusability: The data structure provides reusability means that multiple client programs
can use the data structure.
 Abstraction: The data structure specified by an ADT also provides the level of
abstraction. The client cannot see the internal working of the data structure, so it does not
have to worry about the implementation part. The client can only see the interface.

Primitive vs non-primitive data structure


Primitive data structure Non-primitive data structure

Primitive data structure is a kind of data Non-primitive data structure is a type of data
structure that stores the data of only one structure that can store the data of more than one
type. type.

Examples of primitive data structure are Examples of non-primitive data structure are
integer, character, float. Array, Linked list, stack.

Primitive data structure will contain some Non-primitive data structure can consist of a
value, i.e., it cannot be NULL. NULL value.

The size depends on the type of the data In case of non-primitive data structure, size is not
structure. fixed.

It starts with a lowercase character. It starts with an uppercase character.

Primitive data structure can be used to call Non-primitive data structure cannot be used to call
the methods. the methods.

Damyanti Patel Page 3


Object Oriented Programming & Data Structure

Difference between Linear and Non-linear Data Structures

Linear Data Structure Non-linear Data Structure


In a linear data structure, data elements are
arranged in a linear order where each and every In a non-linear data structure, data elements
element is attached to its previous and next are attached in hierarchically manner.
adjacent.
Whereas in non-linear data structure,
In linear data structure, single level is involved.
multiple levels are involved.
Its implementation is easy in comparison to non- While its implementation is complex in
linear data structure. comparison to linear data structure.
While in non-linear data structure, data
In linear data structure, data elements can be
elements can’t be traversed in a single run
traversed in a single run only.
only.
While in a non-linear data structure, memory
In a linear data structure, memory is not utilized
is utilized in an efficient way.
in an efficient way.
Its examples are: array, stack, queue, linked list,
While its examples are: trees and graphs.
etc.
Applications of non-linear data structures are
Applications of linear data structures are mainly
in Artificial Intelligence and image
in application software development.
processing.

What is a Stack?

A Stack is a linear data structure that follows the LIFO (Last-In-First-Out) principle.

Stack has one end, whereas the Queue has two ends (front and rear).

It contains only one pointer top pointer pointing to the topmost element of the stack.

Whenever an element is added in the stack, it is added on the top of the stack, and the element
can be deleted only from the stack.

In other words, a stack can be defined as a container in which insertion and deletion can be
done from the one end known as the top of the stack.

Damyanti Patel Page 4


Object Oriented Programming & Data Structure

 Application areas of Data Structure


 Data structures are used in any program or software.
 They are used in the areas of
 Compiler Design
 Operating System
 DBMS
 Graphics
 Simulation
 Numerical Analysis
 Artificial Intelligence

Working of Stack

Stack works on the LIFO pattern. As we can observe in the below figure there are five
memory blocks in the stack; therefore, the size of the stack is 5.

Suppose we want to store the elements in a stack and let's assume that stack is empty.

We have taken the stack of size 5 as shown below in which we are pushing the elements one
by one until the stack becomes full.

Damyanti Patel Page 5


Object Oriented Programming & Data Structure

Standard Stack Operations

 push(): When we insert an element in a stack then the operation is known as a push. If
the stack is full then the overflow condition occurs.
 pop(): When we delete an element from the stack, the operation is known as a pop. If the
stack is empty means that no element exists in the stack, this state is known as an
underflow state.
 display() or peep(): It prints all the elements available in the stack.
 isEmpty(): It determines whether the stack is empty or not.
 isFull(): It determines whether the stack is full or not.'
 peek(): It returns the element at the given position.
 count(): It returns the total number of elements available in a stack.
 change(): It changes the element at the given position.

PUSH operation

The steps involved in the PUSH operation is given below:

 Before inserting an element in a stack, we check whether the stack is full.


 If we try to insert the element in a stack, and the stack is full, then the overflow condition
occurs.
 When we initialize a stack, we set the value of top as -1 to check that the stack is empty.
 When the new element is pushed in a stack, first, the value of the top gets incremented,
i.e., top=top+1, and the element will be placed at the new position of the top.
 The elements will be inserted until we reach the max size of the stack.

Damyanti Patel Page 6


Object Oriented Programming & Data Structure

1) PUSH Operation:
It means to insert the elements in the stack. In executing the procedure push, one must first test whether
there is the room in stack for the new item, if not, then the condition is known as overflow.

Algorithm:
Push (Item,n,value)
value=item to push, n=size of stack
Step-1 Set top=-1
Step-2 [Check for empty or full stack]
If (top>=n-1)
Print “Overflow/stack is full”
Return(0)
Else
Step-3 [Increment the stack pointer by one]
Top=top+1
Step-4 [Insert the value to be pushed in the stack at the location of top]
Item [top] =value
Step-5 exit

POP operation

The steps involved in the POP operation is given below:

 Before deleting the element from the stack, we check whether the stack is empty.
 If we try to delete the element from the empty stack, then the underflow condition
occurs.
 If the stack is not empty, we first access the element which is pointed by the top
 Once the pop operation is performed, the top is decremented by 1, i.e., top=top-1.

Damyanti Patel Page 7


Object Oriented Programming & Data Structure

1) POP Operation:

It means to take elements from stack. In executing the procedure pop, one must first test whether there is
an element in the stack to be deleted. If not, then condition is known as underflow.

Algorithm:
Step-1 [Check for empty]
If (top==-1)
Print “Underflow/stack is empty”
Else
Step-2 [Take out the value of the stack where pointer top is pointing]
Value=Item [top]
Step-3 [Decrement the value of top of the stack by one so as to point at the next node to be popped]

Top=top-1
Step-4 return(value) & exit
1) PEEP Operation:

If only information store at some location in a stack is needed, then this operation can be performed. We
move logically to desired location & then fetch the information associated with that location. To access desire
elements from top of the stack is known as Peep Operation. For example suppose we have to access 3 element
from top than it is 2=c, ith=desired element=3 and top=4.the formula is :

E
Top = top-i+1
D
C 2=C = 4-3+1

B = 1+1
A

Algorithm:
Peep(i)
Step-1 [Check for empty]
If (top-i+1<0)
Print “Underflow/stack is empty”
Else
Step-2 [Return ith element from stack]
return(Item[top-i+1])
Step-3 Exit

Damyanti Patel Page 8


Object Oriented Programming & Data Structure

2) UPDATE Operation
It is required when the content of some location in a stack is to be changed suppose one wants to
update information at the ith location in a stack than we first move the pointer to the ith location and than input the
new value of that location.

Algorithm: update(i,value)

Step-1 [Check for underflow condition]

If (top-i+1<0)

Print “Underflow/stack is empty”

Else

Step-2 [Change the element]

Item[top-i+1]=value

Step-3 Exit

Example of Stack(Stack_ex.cpp):

#include<iostream.h>
#include<conio.h>
#include<process.h>
int a[5],top=-1,max=5;
class StackOperation
{
public:
void push();
void pop();
void peep();
void update();
void display();
};
void StackOperation::push()
{
if(top==max-1)
{
cout<<"\nStack is Overflow";
}
else
{
cout<<"\n Enter element for Push:";
cin>>a[++top];
Damyanti Patel Page 9
Object Oriented Programming & Data Structure

}
display();
}
void StackOperation::pop()
{
if(top==-1)
{
cout<<"Stack is underflow";
}
else
{
cout<<"\n Your Poped element is: "<<a[top--];
}
display();
}
void StackOperation::peep()
{
int n;
cout<<"\nEnter the position which you want to get:";
cin>>n;
if(top<n-1)
{
cout<<"\n sorry!! Element does not exit";
}
else
{
cout<<"\n Your Peeped element is: "<<a[n-1];
}
display();
}
void StackOperation::update()
{
int p,v;
cout<<"\nEnter the position which you want to update:";
cin>>p;
if(top<p-1)
{
cout<<"\n sorry!! Element does not exit";
}
else
Damyanti Patel Page 10
Object Oriented Programming & Data Structure

{
cout<<"\nEnter the value:";
cin>>v;
a[p-1]=v;
}
display();
}
void StackOperation::display()
{
int i;
if(top==-1)
{
cout<<"\n Stack is Empty";
}
else
{
for(i=0;i<=top;i++)
{
cout<<"\n "<<a[i];
}
}
}
void main()
{
int ch,n;
StackOperation s1;
do
{
clrscr();
cout<<"\n===========================";
cout<<"\n Stack Operation ";
cout<<"\n===========================";
cout<<"\n 1. PUSH\n 2. POP\n 3. Peep \n 4. Update\n 5. Display \n 6. Exit";
cout<<"\nEnter Your Choice:";
cin>>ch;

switch(ch)
{
case 1:s1.push();break;
case 2:s1.pop();break;
Damyanti Patel Page 11
Object Oriented Programming & Data Structure

case 3:s1.peep();break;
case 4:s1.update();break;
case 5:s1.display();break;
case 6:exit(0); break;
default:cout<<"You Have Wrong Choice";
}
cout<<"\n Do you want to continue (1-Yes 0-No):";
cin>>n;
}while(n!=0);
getch();
}
Stack Application:-

There are two type of stack application.


(1) Polish expression
(2) Recursive
Stack machines, certain computers perform stack operation at the hardware or machine level.
⮞ Polish Expression:

When operators are written after the operands, it is called Reverse Polish Notation.
There are three types of expression:
1) Infix
2) Prefix
3) Postfix

“Pre”,”Post” &”In” refer to the relative position of the operator with respect to the two operands.

1. Infix notation:-
🠆 In this type of expression operators are placed between the operands.
E.g.: A+ (B*C)
🠆 In this notation the order of operations to be performed is determined by the use of parenthesis or by the
use of some operator precedence conventions.
🠆 The levels of precedence are (highest to lowest):

Priority Operator
1 (
2 ^,$,
3 %
4 / or * (left to right)
5 + or –(left to right)
6 )

🠆 During conversion of an infix notation we must begin with inner parenthesis and then precede towards,
the outside expression i.e. the operations with higher precedence are converted first.

Damyanti Patel Page 12


Object Oriented Programming & Data Structure

2. Prefix notation:( K+L-M*N+(O^P)*W/U/V*T+Q++-+KL*MN*//*^OPWVTQ)

In this type of expression operators are placed before operands.


E.g.: +A*BC

Algorithm for converting from infix to prefix:

1. Enter the expression in infix form.


2. Reverse the expression
3. Scan its item character by character (Right to Left)
4. If the item which appears is an operand, add it to the string t (i.e. it is a temporary array of character)
5. If the item is an operator & it is the first operator encountered, push it into the stack. If the operand is )-
closing parenthesis, push it into the stack.
6. If the operator is (- opening parenthesis, pop all the operators from the stack until we encounter ) - closing
parenthesis & add them to the string variable t. pop )-closing parenthesis also from the stack but don’t add
it to the string variable t because in prefix form, there is no need of parenthesis display them. pop (-
opening there is no need of parentheses.
7. If the operator is the second or third operator or any operator except the first, compare the precedence
value of the current operator with the precedence current operator on the top of the stack. If the
precedence value of the current operator is higher than that of the operator on the stack, push the
current operator also onto the stack. But if the precedence value of current operator is smaller; to
the precedence value of the operator on the stack, pop all the operators from the stack until we get
the operator on the top of the stack with precedence value lower than or equal to the precedence
value of the current operator & add these popped operators to string variable t. Then push the
current operator on the stack.
8. When expression is over, pop the entire operator from the stack & add them to the string variable t.
9. Reverse the string array t & display it.

Example: z + (y * x - (w / v ^ u) *t) *s

Input Stack String t


s S
* * S
) *) S
t *) St
* *)* St
) *)*) St
U *)*) Stu
^ *)*)^ Stu
V *)*)^ Stuv
/ *)*)/ stuv^
w *)*)/ stuv^w
( *)* stuv^w/
- *)- stuv^w/*
X *)- stuv^w/*x
* *)-* stuv^w/*x

Damyanti Patel Page 13


Object Oriented Programming & Data Structure

Y *)-* stuv^w/*xy
( * stuv^w/*xy*-
+ + stuv^w/*xy*-*
Z + stuv^w/*xy*-*z
(stack is empty) stuv^w/*xy*-*z+

Prefix notation is: +z*-*yx*/w^vuts

3. Postfix or Suffix or Reverse Polish Notation:-(K+L-M*N+(O^P)*W/U/V*T+QKL+MN*-OP^W*U/V/T*+Q+)

In this type of expression operators are placed after the operands.


E.g.: ABC*+

Algorithm for converting from infix to postfix:

1. Enter the expression in infix form.


2. Scan its item character by character
3. If the item which appears is an operand, display it (i.e. send it to the output)
4. If the item is an operator & it is the first operator encountered, push it into the stack. If the operand is (-
opening parenthesis, push it into the stack.
5. If the operator is )-closing parenthesis, pop all the operators from the stack until we encounter (- opening
parenthesis & display them. pop (- opening there is no need of parentheses.
6. If the operator is the second or third operator or any operator except the first, compare the precedence
value of the current operator with the precedence current operator on the top of the stack. If the
precedence value of the current operator is higher than that of the operator on the stack, push the
current operator also onto the stack. But if the precedence value of current operator is smaller or
equal to the precedence value of the operator on the stack, pop all the operators from the stack
until we get the operator on the top of the stack with precedence value lower than the precedence
value of the current operator & display all these operators. Then push the current operator on the
stack.
7. When expression is over, pop the entire operator from the stack & display them.
Example: (a + b * c ^ d / e) / (f * g - h)

Input Stack String t


( ( -
A ( A
+ (+ A
B (+ Ab
* (+* Ab
C (+* Abc
^ (+*^ Abc
D (+*^ Abcd
/ (+/ abcd^*
E (+/ abcd^*e
) (stack is empty) abcd^*e/+
/ / abcd^*e/+
( /( abcd^*e/+
Damyanti Patel Page 14
Object Oriented Programming & Data Structure

F /( abcd^*e/+f
* /(* abcd^*e/+f
G /(* abcd^*e/+fg
- /(- abcd^*e/+fg*
H /(- abcd^*e/+fg*h
) / abcd^*e/+fg*h-
(stack is empty) abcd^*e/+fg*h-/

Postfix notation is: abcd^*e/+fg*h-/

Example: (A+B) *(C-D)

1) Conversion of Expression Infix to Prefix


= (+AB)*(-CD)
= *+AB-CD

2) Conversion of Expression Infix to Postfix


= (AB+)*(CD-)
= AB+CD-*

⮞ Recursion as an Application of Stack :


🠆 A procedure that contains a procedure which calls itself is called Recursion.
OR
Function call itself called Recursion but here 1st function call 2nd function, 2nd function call 3rd function and so
on.
🠆 Recursion is an important concept in computer science.
🠆 Recursion is less time consuming than normal function.
Advantage of Recursion:
1. Data store in looping.
2. Recursion is a time consuming operation because of pushing all the current variables & objects onto stack.
General Algorithm for Recursion:-
Step-1: [Preface]
Save the argument & return address.
Step-2: [Body of function]
If a base criterion is completed go to step-3.
Else perform partial computation & go to step-1.
Step-3: [Last Section]
Restore the most recently saved parameters & return address.
Example: - Algorithm of recursive factorial.
1. Give an Integer N. this algorithm find factorial N.
2. In this algorithm we will take a stack which is capital A. to store an activation record associated with each
recursive call.
3. Each activation record contains the current value of N & the current return address whenever function is
called. A copy of current argument & current address is push to the stack.
4. Whenever function completed we will fetch or pop current return address & arguments.
Algorithm:
1. [Save N & return address]
Call push(A, N, ret_add)
2. [Is the base criteria found?]
If N==0 then
Fact=1
Damyanti Patel Page 15
Object Oriented Programming & Data Structure
goto step 4
Else
param=N-1
ret_add=step 3
goto step 1
3. [Calculate N!]
Fact=N*fact
4. [Restore N & ret_add]
tem_rec=pop (A) goto tem_rec

Example:
#include<iostream.h>

#include<conio.h>

int factorial(int n);

void main()

int n;

cout << "Enter a positive integer: ";

cin >> n;

cout << "Factorial of " << n << " = " << factorial(n);

getch();

int factorial(int n) {

if(n > 1)

return n * factorial(n - 1);

else

return 1;

Damyanti Patel Page 16

You might also like