You are on page 1of 47

Data Structure

Introduction
Goals of the Course
§Become familiar with some of the fundamental
data structures in computer science

§Improve ability to solve problems abstractly


§ data structures are the building blocks

§Improve ability to analyze your algorithms


§ prove correctness
§ enhance time complexity
Course Syllabus
§Introduction
§Arrays
§Linked Lists
§ Circular Linked Lists
§ Doubly Linked Lists
§Queues & Stacks
§Binary Tree
§Graphs
Problem Solving
• A solution to a problem is computer program
written in programming language which
consist of modules.

• Type of Modules:
• A single, stand-alone function
• A method of a class
• A class
• Several functions or classes working closely together
• Other blocks of code
Problem Solving
A good solution consists of :

• Modules that
– organize data collection to facilitate operations
– must store, move, and alter data
– use algorithms to communicate with one another
Algorithm
• Module implements algorithms

– Algorithm: a step-by-step recipe for performing a


task within a finite period of time
– Algorithms often operate on a collection of data,
which is stored in a structured way in the
computer memory (Data Structure)
– Algorithms: Problem solving using logic
Algorithm
– There are 3 types of algorithm basic control
structure:-
• Sequential
• Selection
• Repeatition (Looping)
Algorithm Example
Algorithm & Data Structure
– Data Structure
• A way of storing and organizing data in a computer so
that it can be used efficiently
• Choosing the right data structure will allow the most
efficient algorithm to be used
• A well-designed data structure :
– allows a variety of critical operations to be
performed
– enable to use few resources, both execution time
and memory space, as possible.
Data Structure
• Operations to the Data Structure
– Traversing- access and process every data in data
structure at least once
– Searching – search for a location of data
– Insertion – insert item in the list of data
– Deletion - delete item from a set of data
– Sorting – sort data in certain order
– Merging – merge multiple group of data
Data Types
• There are two data types:-
1. Basic data types
2. structured data types

Basic Data Types (C++) – store only a single data


– Integral
• Boolean – bool
• Character - char
• Integer – short, int, long
• Floating point – float, double
Data Types
•Unsorted •Sorted Linked
Linked List List
Linked
•Network Structure•Binary Tree
•Array
Storage
•Graph
Structure Structured
Data Types
•Structure
(struct)

State
Structure •Stack
•Queue
Data Types
Storage Structured Data Types
– Array – can contain multiple data with the same
types
– Struct – can contain multiple data with different
type
typedef struct { int age; char
*name;
enum {male, female} gender;
} Person;
Data Types
Linked Data Structure
– Linear Data Structure with restriction
(state Structure)
• Queue & Stack
– Linear Data Structure with no restriction
• Unsorted linked list
• Sorted linked list
– Non-linear Data Structure
• Binary Tree
• Graph
Linear Data Structure with
restriction
• Queue
– First-In-First-Out (FIFO) data structure
– the first element added to the queue will be the
first one to be removed (post office, bank etc)

Out
In
Back Front
Queue Application
Linear Data Structure with
restriction
•Stack
– Based on the principle of Last In First Out (LIFO)
– Stacks are used extensively at every level of a
modern computer system (compiler etc.)
§In Out

Top
Stack Application
Linear Data Structure with no
restriction
• Linked list consists of:
– a sequence of nodes,
– data fields
– one or two links or references pointing to the next
and/or previous nodes

3 12 11
Linear Data Structure with no
restriction
• Sorted linked list
– Data stored in ascending or descending order with
no duplicates
– Insertion at front, middle or rear of the list
– Deletion will not affect the ascending /
descending order of the list
• Unsorted linked list
– A linked list with no ordering
Non-linear Data Structure
• Tree
– A data structure based on a tree structure
– A tree structure is a way of representing the
hierarchical nature of a structure in a graphical
form
– a binary tree is a tree data structure in which each
node has at most two children
– Used for searching big amount of data
Tree

Root
Children of node 20

vertex

leaf

Sibling
Graph
• A graph consists of a set of vertices, and a set
of edges, such that each edge is a connection
between a pair of vertices.

• Some applications require visiting every vertex


in the graph exactly once.
Graph

• The application may require that vertices be visited in


some special order based on graph topology.
• Examples:
– Artificial Intelligence Search (Breadth-first search,
depth first search)
– Shortest paths problems
– Web sites containing a link to and from other
websites.
– Graph that represent courses and the pre-requisites.
Graph Example

Undirected Graph Directed Graph


Network
• Network is a directed graph.
• Can be used to represent a route.
• Example :
– A route for an airline.
– A route for delivery vehicles.
Network Example
• Weighted network that represents a route for a delivery
truck.
• The route shows all cities for the truck to deliver items
and the time taken for a journey from one city to
another.
Review C++ programming
Abstraction
• The purpose of a module is separated from its implementation.

• Specifications for each module are written before


implementation

Abstract data type (ADT)


• A collection of data and a set of operations on the data.

• Given the operations’ specifications, the ADT’s operations can be


used without knowing their implementations or how data is
stored.
Abstraction
Data abstraction
• Focuses on the operations of data (what you can do to a
collection of data), not on the implementation of the
operations (how you do it).

• develop each data structure independently from the rest of


the solution.

Functional abstraction
• Separates the purpose of a module from its implementation
30
Abstraction Example

book
title
abstract to year attributes
author
publisher
price

getData()
print()
checkPrice() behavior
checkPublisher()

Abstraction of a book
31
Encapsulation
• The process of combining data and functions
into a single unit called class.

• The programmer cannot directly access the


data. Data is only accessible through the
functions present inside the class.

• Data encapsulation is an important concept of


data hiding.
32
C++ Classes
• A class defines a new data type.

• A class contains data members and methods


(member functions).

• By default, all members in a class are private


• But can be specified as public
33

• An object is an instance of a class.


C++ Class Definition
class clasName
{
public:
list of data member declaration; class member
list of function member declaration; declarations:
private:
data member
list of data member declaration;
list of function member declaration; and
}; // end class definition function
member

public : members that are accessible by other modules


private : members that are hidden from other modules
and can only be accessed by function member of the
same class.
34
Class Definition for Book
class book{
// data member declaration as private
private
float price;
int year;
char author[20], title[25];
public:book(); // Default constructor
// Constructor with parmeter
book(char *bkTitle,double bkPrice);
book(int = 2000);
// C++ function
void getData();
void print( );
float checkPrice( )const;
char * getAuthor();
~book() ; // destructor
}; // end book declaration
35
Class Methods

Class methods consists of


– Constructor
– Destructor
– C++ functions.
– const function

36
Constructors
– Used to create and initialize new instances of a class
– Is invoked when an instance of a class is declared

– Have the same name as the class

– Have no return type, not even void

• A class can have several constructors


– However, compiler will generate a default
constructor if no constructor is defined. 37
Constructor Properties
• More than one constructor can be
declared.
• Each constructor must be distinguished by
the arguments.
book();
book(char *bkTitle,double bkPrice); book(int = 2000);

• Default constructor: book();

• Can have argument:


book(char *bkTitle,double bkPrice);

• Can have default argument: 38

book(int = 2000);
Default Constructor Implementation
• Sets data members to initial values
book::book(){
price = 10.00;
strcpy (author,”Dayang Norhayati”);
strcpy (title, “Learn Data Structure”);
year = 2012;
}
// end default constructor

Instance declaration:
book myBook;
Instance myBook is created with the price set to 10.0, author
39 set to
Dayang Norhayati, title set to Learn Data Structure and year set to
2012
Constructor with Argument
Implementation

book::book (char *bkTitle,double bkPrice)


{ strcpy (title, bkTitle);
price = bkPrice;
}

Instance declaration:
book myBook(“NorBahiah”,25.00);

Price is set to 25.00 Author is set to


NorBahiah
40
Constructor With Default
Argument
Implementation
book::book(int year);
// Constructor with default argument
{ price = 10.00;
strcpy (author,”NorBahiah”);
strcpy (title, “Learn C++”);
} // end default constructor

There are 2 methods of to declare instance of a class:


book myBook; // set year to default value, 2000 book
yourBook(2009); // set year to 2009

Avoid ambiguity error - when implementing constructor with default


argument
Destructor
• Destroys an instance of an object when
the object’s lifetime ends.
• Each class has one destructor.
– The compiler will generate a destructor if the
destructor is not defined.
• Example: ~book();
book::~book()
{ cout << "\nDestroy the book with title "
<< title;
}
42
Function Member Implementation
void book::getData(){
cout << "\nEnter author's name : ";
cin >> author;
cout << "\nEnter book title : ";
cin >> title;
}

Method to call the member function:


•From main() or non-member function
cout << myBook.getData() << endl;
const member function – cannot alter value
float book::checkPrice( )const
{ return price; }
43
Classes as Function Parameters
• Class objects can be passed to another function as
parameters
• Passing class as parameter to function can be done
using:

• Pass by value – Any changes that the function makes to


the object is not reflected in the corresponding actual
argument in the calling function.

• Pass by reference - Any changes that the function makes


to the object will change the corresponding actual
argument in the calling function. 44
Array of class
• A group of objects from the same class can be
declared as array of a class.

• Example:
▫ Array of class students registered in Data Structure class
▫ Array of class lecturer teaching at FCI.
▫ Array of class subjects offered in Semester II.

• Every element in the array of class has it’s own


data member and function member.
45

• Syntax to declare array of objects :


className arrayName[arraySize];
Array of class Example
class staff {
char name[20];
int age ;
float salary;

public:
void read_data()
{ cin >> name >> age >> salary; }
void print_data()
{ cout << name << age << salary; }
} ;

main() Declare 20 managersfrom


{ class staff. Each element of
staff manager[20]; manager has name,
// declare array of staff age and salary.
}

46
Array of class Example
There are 2 methods to call member function for manager
array.
1. By using array subscript in order to access manager in
certain location of the array.
cin >> n ;
manager[n].read_data() ;
cout << manager[n].print_data() ;

2. By using loop in order to access a group of


managers.
// read information for 10 managers
for ( int x = 0 ; x < 10; x++ )
manager[x].read_data();
// print information of 10 managers 47
for ( int y = 0 ; y < 10; y++ )
manager[y].print_data();

You might also like