SlideShare a Scribd company logo
DATA STRUCTURES
AND
ALGORITHMS
Lecture Notes 3
Prepared by İnanç TAHRALI
2
ROAD MAP
 Abstract Data Types (ADT)
 The List ADT
 Implementation of Lists

Array implementation of lists

Linked list implementation of lists

Cursor implementation of lists
3
Abstract Data Types (ADT)
 Definition :
Is a set of operation
Mathematical abstraction
No implementation detail
 Example :
Lists, sets, graphs, stacks are examples of
ADT along with their operations
4
Why ADT ?
 Modularity
 divide program into small functions
 easy to debug and maintain
 easy to modify
 group work
 Reuse
 do some operations only once
 Easy to change of implementation
 transparent to the program
5
THE LIST ADT
 Ordered sequence of data items called
elements
 A1, A2, A3, …,AN is a list of size N
 size of an empty list is 0
 Ai+1 succeeds Ai
 Ai-1 preceeds Ai
 position of Ai is i
 first element is A1 called “head”
 last element is AN called “tail”
Operations ?
6
THE LIST ADT
 Operations
 PrintList
 Find
 FindKth
 Insert
 Delete
 Next
 Previous
 MakeEmpty
7
THE LIST ADT
 Example:
the elements of a list are
34, 12, 52, 16, 12
 Find (52)  3
 Insert (20, 3)  34, 12, 52, 20, 16, 12
 Delete (52)  34, 12, 20, 16, 12
 FindKth (3)  20
8
Implementation of Lists
 Many Implementations
 Array
 Linked List
 Cursor (linked list using arrays)
9
ROAD MAP
 Abstract Data Types (ADT)
 The List ADT
 Implementation of Lists

Array implementation of lists

Linked list implementation of lists

Cursor implementation of lists
10
Array Implementation of List ADT
 Need to define a size for array
 High overestimate (waste of space)
 Operations Running Times
PrintList O(N)
Find
Insert O(N) (on avarage half needs to be moved)
Delete
FindKth
Next O(1)
Previous
11
Array Implementation of List ADT
 Disadvantages :
 insertion and deletion is very slow

need to move elements of the list
 redundant memory space

it is difficult to estimate the size of array
12
ROAD MAP
 Abstract Data Types (ADT)
 The List ADT
 Implementation of Lists

Array implementation of lists

Linked list implementation of lists

Cursor implementation of lists
13
Linked List Implementation of Lists
 Series of nodes
 not adjacent in memory
 contain the element and a pointer to a node containing its
succesor
 Avoids the linear cost of insertion and deletion !
14
Linked List Implementation of Lists
 Insertion into a linked list
15
Linked List Implementation of Lists
 Deletion from a linked list
16
Linked List Implementation of Lists
 Need to know where the first node is
 the rest of the nodes can be accessed
 No need to move the list for insertion and
deletion operations
 No memory waste
17
Linked List Implementation of Lists
Linked List Array
PrintList O(N) (traverse the list)
O(N)
Find
FindKth (L,i) O(i)
O(1)
Delete O(1)
O(N)
18
Programming Details
 There are 3 special cases for linked lists
 Insert an element at the front of the list

there is no really obvious way
 Delete an element from the front of the list

changes the start of the list
 Delete an element in general

requires to keep track of the node before the deleted one
How can we solve these three problems ?
19
Programming Details
Keep a header node in position 0
 Write a FindPrevious routine
 returns the predecessor of the cell
 To delete the first element
 FindPrevious routine returns the position of
header
Use of header node is controversial !
20
Type decleration for link list node
template <class Object>
class List; // Incomplete declaration.
template <class Object>
class ListItr; // Incomplete declaration.
template <class Object>
class ListNode {
ListNode( const Object & theElement = Object( ),
ListNode*n=NULL) : element(theElement),next(n)
{}
Object element;
ListNode *next;
friend class List<Object>;
friend class ListItr<Object>;
};
21
Iterator class for linked lists
template <class Object>
class ListItr {
public:
ListItr( ) : current( NULL ) { }
bool isPastEnd( ) const { return current == NULL; }
void advance( )
{ if( !isPastEnd( ) ) current = current->next; }
const Object & retrieve( ) const
{ if( isPastEnd( ) )
throw BadIterator( );
return current->element; }
private:
ListNode<Object> *current; // Current position
ListItr(ListNode<Object> *theNode):current( theNode ) { }
friend class List<Object>; // Grant access to constructor
};
22
List class interface
template <class Object>
class List {
public:
List( );
List( const List & rhs );
~List( );
bool isEmpty( ) const;
void makeEmpty( );
ListItr<Object> zeroth( ) const;
ListItr<Object> first( ) const;
void insert( const Object & x, const ListItr<Object> & p );
ListItr<Object> find( const Object & x ) const;
ListItr<Object> findPrevious( const Object & x ) const;
void remove( const Object & x );
const List & operator=( const List & rhs );
private:
ListNode<Object> *header;
};
23
Function to print a list
template <class Object>
void printList( const List<Object> &the List)
{
if (theList.isEmpty())
cout<< “Empty list” << endl;
else
{
ListItr<Object> itr = theList.first();
for (; !itr.isPastEnd(); itr.advance())
cout << itr.retrieve() <<“ ”;
}
cout << endl;
}
24
Some list one-liners
/* Construct the list */
template <class Object>
List<Object>::List( )
{
header = new ListNode<Object>;
}
/* Test if the list is logically empty */
template <class Object>
bool List<Object>::isEmpty( ) const
{
return header->next == NULL;
}
25
Some list one liners
/* Return an iterator representing the header node
template <class Object>
ListItr<Object> List<Object>::zeroth( ) const
{
return ListItr<Object>( header );
}
/* Return an iterator representing the first node
in the list. This operation is valid for empty
lists. */
template <class Object>
ListItr<Object> List<Object>::first( ) const
{
return ListItr<Object>( header->next );
}
26
Find routine
/* Return iterator corresponding to the first
node containing an item x. Iterator isPastEnd
if item is not found. */
template <class Object>
ListItr<Object> List<Object>::find( const
Object & x ) const
{
ListNode<Object> *itr = header->next;
while( itr != NULL && itr->element != x )
itr = itr->next;
return ListItr<Object>( itr );
}
27
Deletion routine for linked lists
/* Remove the first occurrence of an item x. */
template <class Object>
void List<Object>::remove( const Object & x )
{
ListItr<Object> p = findPrevious( x );
if( p.current->next != NULL )
{
ListNode<Object> *oldNode = p.current->next;
p.current->next = p.current->next->next;
delete oldNode;
}
}
28
findPrevious-the find routine for
use with remove
/*Return iterator prior to the first node containing an
item x.
template <class Object>
ListItr<Object> List<Object>::findPrevious( const Object &
x ) const
{
ListNode<Object> *itr = header;
while( itr->next != NULL && itr->next->element != x )
itr = itr->next;
return ListItr<Object>( itr );
}
29
Insertion routine for linked lists
/* Insert item x after p. */
template <class Object>
void List<Object>::insert( const Object & x,
const ListItr<Object> & p )
{
if( p.current != NULL )
p.current->next = new ListNode<Object>
( x, p.current->next );
}
30
makeEmpty and List destructor
/* Make the list logically empty. */
template <class Object>
void List<Object>::makeEmpty( )
{
while( !isEmpty( ) )
remove( first( ).retrieve( ) );
}
/* Destructor */
template <class Object>
List<Object>::~List( )
{
makeEmpty( );
delete header;
}
31
List copy routines: operator=
/*Deep copy of linked lists.
template <class Object>
const List<Object> & List<Object>::operator=( const
List<Object> & rhs )
{
ListItr<Object> ritr = rhs.first( );
ListItr<Object> itr = zeroth( );
if( this != &rhs )
{
makeEmpty( );
for( ; !ritr.isPastEnd( );
ritr.advance( ),itr.advance( ))
insert( ritr.retrieve( ), itr );
}
return *this;
}
32
List copy routines : copy constructor
/* Copy constructor
template <class Object>
List<Object>::List( const List<Object> & rhs )
{
header = new ListNode<Object>;
*this = rhs;
}
33
Doubly Linked List
 Traversing list backwards
 not easy with regular lists
 Insertion and deletion more pointer fixing
 Deletion is easier
 Previous node is easy to find
34
Circulary Linked List
 Last node points the first
35
ROAD MAP
 Abstract Data Types (ADT)
 The List ADT
 Implementation of Lists

Array implementation of lists

Linked list implementation of lists

Cursor implementation of lists
36
Cursor Implementation of Linked List
Problems with linked list implementation:
 Same language do not support pointers !
 Then how can you use linked lists ?
 new and free operations are slow
 Actually not constant time
37
Cursor Implementation of Linked List
SOLUTION: Implement linked list on an array
called CURSOR
38
Cursor Implementation of Linked List
 Cursor operation simulates the features
 Collection of structures

uses array for nodes
 Array index is pointer
 new and delete operation

Keep a free list
 new returns an element from freelist
 delete place the node in freelist

Freelist
 Use cell 0 as header
 All nodes are free initially
 0 is a NULL pointer
39
Cursor Implementation of Linked List
If L = 5, then L represents list (A, B, E)
If M = 3, then M represents list (C, D, F)
40
Iterator for cursor implementation
of linked lists
template <class Object>
class ListItr
{
public:
ListItr( ) : current( 0 ) { }
bool isPastEnd( ) const {return current == 0; }
void advance( ){
if( !isPastEnd( ) )
current = List<Object>::cursorSpace[ current ].next; }
const Object & retrieve( ) const {
if( isPastEnd( ) ) throw BadIterator( );
return List<Object>::cursorSpace[ current ].element; }
private:
int current; // Current position
friend class List<Object>;
ListItr( int theNode ) : current( theNode ) { }
};
41
Class skeleton for cursor-based List
template <class Object>
class ListItr; // Incomplete declaration.
template <class Object>
class List
{
public:
List( );
List( const List & rhs );
~List( );
bool isEmpty( ) const;
void makeEmpty( );
ListItr<Object> zeroth( ) const;
ListItr<Object> first( ) const;
void insert( const Object & x, const ListItr<Object> & p );
ListItr<Object> find( const Object & x ) const;
ListItr<Object> findPrevious( const Object & x ) const;
void remove( const Object & x );
42
Class skeleton for cursor-based List
public:
struct CursorNode
{
CursorNode( ) : next( 0 ) { }
private:
CursorNode( const Object & theElement, int n )
: element( theElement ), next( n ) {}
Object element;
int next;
friend class List<Object>;
friend class ListItr<Object>;
};
const List & operator=( const List & rhs );
43
Class skeleton for cursor-based List
private:
int header;
static vector<CursorNode> cursorSpace;
static void initializeCursorSpace( );
static int alloc( );
static void free( int p );
friend class ListItr<Object>;
};
44
cursorSpace initialization
/* Routine to initialize the cursorSpace. */
template <class Object>
void List<Object>::initializeCursorSpace( )
{
static int cursorSpaceIsInitialized = false;
if( !cursorSpaceIsInitialized )
{
cursorSpace.resize( 100 );
for( int i = 0; i < cursorSpace.size( ); i++ )
cursorSpace[ i ].next = i + 1;
cursorSpace[ cursorSpace.size( ) - 1 ].next = 0;
cursorSpaceIsInitialized = true;
}
}
45
Routines : alloc and free
/* Allocate a CursorNode
template <class Object>
int List<Object>::alloc( )
{
int p = cursorSpace[ 0 ].next;
cursorSpace[ 0 ].next = cursorSpace[ p ].next;
return p;
}
/* Free a CursorNode
template <class Object>
void List<Object>::free( int p )
{
cursorSpace[ p ].next = cursorSpace[ 0 ].next;
cursorSpace[ 0 ].next = p;
}
46
Short routines for cursor-based lists
/* Construct the list
template <class Object>
List<Object>::List( )
{
initializeCursorSpace( );
header = alloc( );
cursorSpace[ header ].next = 0;
}
/* Destroy the list
template <class Object>
List<Object>::~List( )
{
makeEmpty( );
free( header );
}
47
Short routines for cursor-based lists
/* Test if the list is logically empty. return true if
empty
template <class Object>
bool List<Object>::isEmpty( ) const
{
return cursorSpace[ header ].next == 0;
}
/* Return an iterator representing the first node in
the list. This operation is valid for empty lists.
template <class Object>
ListItr<Object> List<Object>::first( ) const
{
return ListItr<Object>( cursorSpace[ header ].next );
}
48
find routine - cursor implementation
/*Return iterator corresponding to the first node containing
an item x. Iterator isPastEnd if item is not found.
template <class Object>
ListItr<Object> List<Object>::find( const Object & x ) const
{
int itr = cursorSpace[ header ].next;
while( itr != 0 && cursorSpace[ itr ].element != x )
itr = cursorSpace[ itr ].next;
return ListItr<Object>( itr );
}
49
insertion routine-cursor implementation
/* Insert item x after p.
template <class Object>
void List<Object>::insert(const Object & x,const ListItr<Object> & p)
{
if( p.current != 0 )
{
int pos = p.current;
int tmp = alloc( );
cursorSpace[ tmp ] = CursorNode( x, cursorSpace[ pos ].next );
cursorSpace[ pos ].next = tmp;
}
}
50
deletion routine - cursor implementation
/* Remove the first occurrence of an item x.
template <class Object>
void List<Object>::remove( const Object & x )
{
ListItr<Object> p = findPrevious( x );
int pos = p.current;
if( cursorSpace[ pos ].next != 0 )
{
int tmp = cursorSpace[ pos ].next;
cursorSpace[ pos ].next = cursorSpace[ tmp ].next;
free ( tmp );
}
}

More Related Content

What's hot (20)

PPTX
Python Data Structures and Algorithms.pptx
ShreyasLawand
 
PPTX
Terminology of tree
RacksaviR
 
PPTX
Doubly Linked List
Ninad Mankar
 
PPT
Data structure lecture 1
Kumar
 
PPTX
Stack and Queue
Apurbo Datta
 
PPTX
Circular link list.ppt
Tirthika Bandi
 
PPTX
Arrays in Data Structure and Algorithm
KristinaBorooah
 
PPTX
Data structure Stack
Praveen Vishwakarma
 
PPTX
Data Structure and Algorithms.pptx
Syed Zaid Irshad
 
PDF
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
PDF
Data Structures
Prof. Dr. K. Adisesha
 
PPTX
queue & its applications
somendra kumar
 
DOC
CS8391 Data Structures 2 mark Questions - Anna University Questions
P. Subathra Kishore, KAMARAJ College of Engineering and Technology, Madurai
 
PPT
Two Dimensional Array
dincyjain
 
PPTX
Relational Algebra,Types of join
raj upadhyay
 
PDF
UNIT I LINEAR DATA STRUCTURES – LIST
Kathirvel Ayyaswamy
 
PPTX
Types of Tree in Data Structure in C++
Himanshu Choudhary
 
PPTX
Stack using Linked List
Sayantan Sur
 
PPTX
SQL Data types and Constarints.pptx
jaba kumar
 
PPTX
Data Structures (CS8391)
Elavarasi K
 
Python Data Structures and Algorithms.pptx
ShreyasLawand
 
Terminology of tree
RacksaviR
 
Doubly Linked List
Ninad Mankar
 
Data structure lecture 1
Kumar
 
Stack and Queue
Apurbo Datta
 
Circular link list.ppt
Tirthika Bandi
 
Arrays in Data Structure and Algorithm
KristinaBorooah
 
Data structure Stack
Praveen Vishwakarma
 
Data Structure and Algorithms.pptx
Syed Zaid Irshad
 
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
Data Structures
Prof. Dr. K. Adisesha
 
queue & its applications
somendra kumar
 
CS8391 Data Structures 2 mark Questions - Anna University Questions
P. Subathra Kishore, KAMARAJ College of Engineering and Technology, Madurai
 
Two Dimensional Array
dincyjain
 
Relational Algebra,Types of join
raj upadhyay
 
UNIT I LINEAR DATA STRUCTURES – LIST
Kathirvel Ayyaswamy
 
Types of Tree in Data Structure in C++
Himanshu Choudhary
 
Stack using Linked List
Sayantan Sur
 
SQL Data types and Constarints.pptx
jaba kumar
 
Data Structures (CS8391)
Elavarasi K
 

Viewers also liked (15)

PPT
Cursor implementation
vicky201
 
PPTX
Data structures and algorithms
Harry Potter
 
PDF
Linked lists
Piyush Mittal
 
PPT
358 33 powerpoint-slides_8-linked-lists_chapter-8
sumitbardhan
 
PPT
data structure
hashim102
 
PDF
Data structures and algorithms made easy
CareerMonk Publications
 
PPT
Introduction of data structure
eShikshak
 
PDF
C++ idioms by example (Nov 2008)
Olve Maudal
 
PPTX
linked list
Mohaimin Rahat
 
PDF
Solid C++ by Example
Olve Maudal
 
PDF
How A Compiler Works: GNU Toolchain
National Cheng Kung University
 
PPTX
Data structures and algorithms
Julie Iskander
 
PPTX
Linked list
akshat360
 
PDF
TDD in C - Recently Used List Kata
Olve Maudal
 
PDF
Deep C
Olve Maudal
 
Cursor implementation
vicky201
 
Data structures and algorithms
Harry Potter
 
Linked lists
Piyush Mittal
 
358 33 powerpoint-slides_8-linked-lists_chapter-8
sumitbardhan
 
data structure
hashim102
 
Data structures and algorithms made easy
CareerMonk Publications
 
Introduction of data structure
eShikshak
 
C++ idioms by example (Nov 2008)
Olve Maudal
 
linked list
Mohaimin Rahat
 
Solid C++ by Example
Olve Maudal
 
How A Compiler Works: GNU Toolchain
National Cheng Kung University
 
Data structures and algorithms
Julie Iskander
 
Linked list
akshat360
 
TDD in C - Recently Used List Kata
Olve Maudal
 
Deep C
Olve Maudal
 
Ad

Similar to Data structures & algorithms lecture 3 (20)

PPTX
List,Stacks and Queues.pptx
UmatulSaboohSaleem1
 
PPT
DSA Leactrure # 1! Explaining abstract data types
amazonventuresinfo
 
PPT
Chapter 5 ds
Hanif Durad
 
PPT
12888239 (2).ppt
SrinivasanCSE
 
PPT
Array linked list.ppt
Waf1231
 
PPT
Lists
Ghaffar Khan
 
PPT
List
Amit Vats
 
PDF
DS Complete notes for Computer science and Engineering
RAJASEKHARV8
 
PPTX
Chapter 15 Lists
Praveen M Jigajinni
 
PPTX
General Data structures
Youssef Elsalhawy
 
PPT
03-Lists.ppt
huynguyen556776
 
PPT
3.ppt
ArifKamal36
 
PPT
3.ppt
ArifKamal36
 
PPT
1 list datastructures
Nguync91368
 
PDF
javacollections.pdf
ManojKandhasamy1
 
PPT
LINKEDb2bb22bb3b3b3b3n3_LIST_UKL_1-2.ppt
Farhana859326
 
PPTX
Data -structures for class 12 , easy ppt
anikedheikhamsingh
 
PPTX
EC2311 – Data Structures and C Programming
Padma Priya
 
PPTX
16. Arrays Lists Stacks Queues
Intro C# Book
 
PPT
Lecture 3 List of Data Structures & Algorithms
haseebanjum2611
 
List,Stacks and Queues.pptx
UmatulSaboohSaleem1
 
DSA Leactrure # 1! Explaining abstract data types
amazonventuresinfo
 
Chapter 5 ds
Hanif Durad
 
12888239 (2).ppt
SrinivasanCSE
 
Array linked list.ppt
Waf1231
 
List
Amit Vats
 
DS Complete notes for Computer science and Engineering
RAJASEKHARV8
 
Chapter 15 Lists
Praveen M Jigajinni
 
General Data structures
Youssef Elsalhawy
 
03-Lists.ppt
huynguyen556776
 
1 list datastructures
Nguync91368
 
javacollections.pdf
ManojKandhasamy1
 
LINKEDb2bb22bb3b3b3b3n3_LIST_UKL_1-2.ppt
Farhana859326
 
Data -structures for class 12 , easy ppt
anikedheikhamsingh
 
EC2311 – Data Structures and C Programming
Padma Priya
 
16. Arrays Lists Stacks Queues
Intro C# Book
 
Lecture 3 List of Data Structures & Algorithms
haseebanjum2611
 
Ad

More from Poojith Chowdhary (20)

PPT
Voltage multiplier
Poojith Chowdhary
 
PPT
Implementation of MIS and its methods
Poojith Chowdhary
 
PPT
THE LIGHT EMITTING DIODE
Poojith Chowdhary
 
PPT
High k dielectric
Poojith Chowdhary
 
PPTX
The science of thought
Poojith Chowdhary
 
PPT
Child prodigy,savant and late boomers
Poojith Chowdhary
 
PPTX
Us wireless cable television
Poojith Chowdhary
 
PPTX
1116297 634468886714442500
Poojith Chowdhary
 
PPTX
Photo transistors
Poojith Chowdhary
 
PPT
8086 micro processor
Poojith Chowdhary
 
PPT
8051 micro controller
Poojith Chowdhary
 
PPT
8085 micro processor
Poojith Chowdhary
 
PPTX
Quantum mechanics
Poojith Chowdhary
 
PPTX
Function generator
Poojith Chowdhary
 
PPTX
Resistors
Poojith Chowdhary
 
PPT
The new seven wonders of the world
Poojith Chowdhary
 
PPT
Abstract data types
Poojith Chowdhary
 
PPT
The new seven wonders of the world
Poojith Chowdhary
 
PPTX
Animal lifecycles
Poojith Chowdhary
 
PPTX
Resistors
Poojith Chowdhary
 
Voltage multiplier
Poojith Chowdhary
 
Implementation of MIS and its methods
Poojith Chowdhary
 
THE LIGHT EMITTING DIODE
Poojith Chowdhary
 
High k dielectric
Poojith Chowdhary
 
The science of thought
Poojith Chowdhary
 
Child prodigy,savant and late boomers
Poojith Chowdhary
 
Us wireless cable television
Poojith Chowdhary
 
1116297 634468886714442500
Poojith Chowdhary
 
Photo transistors
Poojith Chowdhary
 
8086 micro processor
Poojith Chowdhary
 
8051 micro controller
Poojith Chowdhary
 
8085 micro processor
Poojith Chowdhary
 
Quantum mechanics
Poojith Chowdhary
 
Function generator
Poojith Chowdhary
 
The new seven wonders of the world
Poojith Chowdhary
 
Abstract data types
Poojith Chowdhary
 
The new seven wonders of the world
Poojith Chowdhary
 
Animal lifecycles
Poojith Chowdhary
 

Recently uploaded (20)

PPTX
Controller Request and Response in Odoo18
Celine George
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PPTX
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
PPTX
Quarter 1_PPT_PE & HEALTH 8_WEEK 3-4.pptx
ronajadolpnhs
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PDF
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
Horarios de distribución de agua en julio
pegazohn1978
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
Controller Request and Response in Odoo18
Celine George
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
Quarter 1_PPT_PE & HEALTH 8_WEEK 3-4.pptx
ronajadolpnhs
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Horarios de distribución de agua en julio
pegazohn1978
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 

Data structures & algorithms lecture 3

  • 1. DATA STRUCTURES AND ALGORITHMS Lecture Notes 3 Prepared by İnanç TAHRALI
  • 2. 2 ROAD MAP  Abstract Data Types (ADT)  The List ADT  Implementation of Lists  Array implementation of lists  Linked list implementation of lists  Cursor implementation of lists
  • 3. 3 Abstract Data Types (ADT)  Definition : Is a set of operation Mathematical abstraction No implementation detail  Example : Lists, sets, graphs, stacks are examples of ADT along with their operations
  • 4. 4 Why ADT ?  Modularity  divide program into small functions  easy to debug and maintain  easy to modify  group work  Reuse  do some operations only once  Easy to change of implementation  transparent to the program
  • 5. 5 THE LIST ADT  Ordered sequence of data items called elements  A1, A2, A3, …,AN is a list of size N  size of an empty list is 0  Ai+1 succeeds Ai  Ai-1 preceeds Ai  position of Ai is i  first element is A1 called “head”  last element is AN called “tail” Operations ?
  • 6. 6 THE LIST ADT  Operations  PrintList  Find  FindKth  Insert  Delete  Next  Previous  MakeEmpty
  • 7. 7 THE LIST ADT  Example: the elements of a list are 34, 12, 52, 16, 12  Find (52)  3  Insert (20, 3)  34, 12, 52, 20, 16, 12  Delete (52)  34, 12, 20, 16, 12  FindKth (3)  20
  • 8. 8 Implementation of Lists  Many Implementations  Array  Linked List  Cursor (linked list using arrays)
  • 9. 9 ROAD MAP  Abstract Data Types (ADT)  The List ADT  Implementation of Lists  Array implementation of lists  Linked list implementation of lists  Cursor implementation of lists
  • 10. 10 Array Implementation of List ADT  Need to define a size for array  High overestimate (waste of space)  Operations Running Times PrintList O(N) Find Insert O(N) (on avarage half needs to be moved) Delete FindKth Next O(1) Previous
  • 11. 11 Array Implementation of List ADT  Disadvantages :  insertion and deletion is very slow  need to move elements of the list  redundant memory space  it is difficult to estimate the size of array
  • 12. 12 ROAD MAP  Abstract Data Types (ADT)  The List ADT  Implementation of Lists  Array implementation of lists  Linked list implementation of lists  Cursor implementation of lists
  • 13. 13 Linked List Implementation of Lists  Series of nodes  not adjacent in memory  contain the element and a pointer to a node containing its succesor  Avoids the linear cost of insertion and deletion !
  • 14. 14 Linked List Implementation of Lists  Insertion into a linked list
  • 15. 15 Linked List Implementation of Lists  Deletion from a linked list
  • 16. 16 Linked List Implementation of Lists  Need to know where the first node is  the rest of the nodes can be accessed  No need to move the list for insertion and deletion operations  No memory waste
  • 17. 17 Linked List Implementation of Lists Linked List Array PrintList O(N) (traverse the list) O(N) Find FindKth (L,i) O(i) O(1) Delete O(1) O(N)
  • 18. 18 Programming Details  There are 3 special cases for linked lists  Insert an element at the front of the list  there is no really obvious way  Delete an element from the front of the list  changes the start of the list  Delete an element in general  requires to keep track of the node before the deleted one How can we solve these three problems ?
  • 19. 19 Programming Details Keep a header node in position 0  Write a FindPrevious routine  returns the predecessor of the cell  To delete the first element  FindPrevious routine returns the position of header Use of header node is controversial !
  • 20. 20 Type decleration for link list node template <class Object> class List; // Incomplete declaration. template <class Object> class ListItr; // Incomplete declaration. template <class Object> class ListNode { ListNode( const Object & theElement = Object( ), ListNode*n=NULL) : element(theElement),next(n) {} Object element; ListNode *next; friend class List<Object>; friend class ListItr<Object>; };
  • 21. 21 Iterator class for linked lists template <class Object> class ListItr { public: ListItr( ) : current( NULL ) { } bool isPastEnd( ) const { return current == NULL; } void advance( ) { if( !isPastEnd( ) ) current = current->next; } const Object & retrieve( ) const { if( isPastEnd( ) ) throw BadIterator( ); return current->element; } private: ListNode<Object> *current; // Current position ListItr(ListNode<Object> *theNode):current( theNode ) { } friend class List<Object>; // Grant access to constructor };
  • 22. 22 List class interface template <class Object> class List { public: List( ); List( const List & rhs ); ~List( ); bool isEmpty( ) const; void makeEmpty( ); ListItr<Object> zeroth( ) const; ListItr<Object> first( ) const; void insert( const Object & x, const ListItr<Object> & p ); ListItr<Object> find( const Object & x ) const; ListItr<Object> findPrevious( const Object & x ) const; void remove( const Object & x ); const List & operator=( const List & rhs ); private: ListNode<Object> *header; };
  • 23. 23 Function to print a list template <class Object> void printList( const List<Object> &the List) { if (theList.isEmpty()) cout<< “Empty list” << endl; else { ListItr<Object> itr = theList.first(); for (; !itr.isPastEnd(); itr.advance()) cout << itr.retrieve() <<“ ”; } cout << endl; }
  • 24. 24 Some list one-liners /* Construct the list */ template <class Object> List<Object>::List( ) { header = new ListNode<Object>; } /* Test if the list is logically empty */ template <class Object> bool List<Object>::isEmpty( ) const { return header->next == NULL; }
  • 25. 25 Some list one liners /* Return an iterator representing the header node template <class Object> ListItr<Object> List<Object>::zeroth( ) const { return ListItr<Object>( header ); } /* Return an iterator representing the first node in the list. This operation is valid for empty lists. */ template <class Object> ListItr<Object> List<Object>::first( ) const { return ListItr<Object>( header->next ); }
  • 26. 26 Find routine /* Return iterator corresponding to the first node containing an item x. Iterator isPastEnd if item is not found. */ template <class Object> ListItr<Object> List<Object>::find( const Object & x ) const { ListNode<Object> *itr = header->next; while( itr != NULL && itr->element != x ) itr = itr->next; return ListItr<Object>( itr ); }
  • 27. 27 Deletion routine for linked lists /* Remove the first occurrence of an item x. */ template <class Object> void List<Object>::remove( const Object & x ) { ListItr<Object> p = findPrevious( x ); if( p.current->next != NULL ) { ListNode<Object> *oldNode = p.current->next; p.current->next = p.current->next->next; delete oldNode; } }
  • 28. 28 findPrevious-the find routine for use with remove /*Return iterator prior to the first node containing an item x. template <class Object> ListItr<Object> List<Object>::findPrevious( const Object & x ) const { ListNode<Object> *itr = header; while( itr->next != NULL && itr->next->element != x ) itr = itr->next; return ListItr<Object>( itr ); }
  • 29. 29 Insertion routine for linked lists /* Insert item x after p. */ template <class Object> void List<Object>::insert( const Object & x, const ListItr<Object> & p ) { if( p.current != NULL ) p.current->next = new ListNode<Object> ( x, p.current->next ); }
  • 30. 30 makeEmpty and List destructor /* Make the list logically empty. */ template <class Object> void List<Object>::makeEmpty( ) { while( !isEmpty( ) ) remove( first( ).retrieve( ) ); } /* Destructor */ template <class Object> List<Object>::~List( ) { makeEmpty( ); delete header; }
  • 31. 31 List copy routines: operator= /*Deep copy of linked lists. template <class Object> const List<Object> & List<Object>::operator=( const List<Object> & rhs ) { ListItr<Object> ritr = rhs.first( ); ListItr<Object> itr = zeroth( ); if( this != &rhs ) { makeEmpty( ); for( ; !ritr.isPastEnd( ); ritr.advance( ),itr.advance( )) insert( ritr.retrieve( ), itr ); } return *this; }
  • 32. 32 List copy routines : copy constructor /* Copy constructor template <class Object> List<Object>::List( const List<Object> & rhs ) { header = new ListNode<Object>; *this = rhs; }
  • 33. 33 Doubly Linked List  Traversing list backwards  not easy with regular lists  Insertion and deletion more pointer fixing  Deletion is easier  Previous node is easy to find
  • 34. 34 Circulary Linked List  Last node points the first
  • 35. 35 ROAD MAP  Abstract Data Types (ADT)  The List ADT  Implementation of Lists  Array implementation of lists  Linked list implementation of lists  Cursor implementation of lists
  • 36. 36 Cursor Implementation of Linked List Problems with linked list implementation:  Same language do not support pointers !  Then how can you use linked lists ?  new and free operations are slow  Actually not constant time
  • 37. 37 Cursor Implementation of Linked List SOLUTION: Implement linked list on an array called CURSOR
  • 38. 38 Cursor Implementation of Linked List  Cursor operation simulates the features  Collection of structures  uses array for nodes  Array index is pointer  new and delete operation  Keep a free list  new returns an element from freelist  delete place the node in freelist  Freelist  Use cell 0 as header  All nodes are free initially  0 is a NULL pointer
  • 39. 39 Cursor Implementation of Linked List If L = 5, then L represents list (A, B, E) If M = 3, then M represents list (C, D, F)
  • 40. 40 Iterator for cursor implementation of linked lists template <class Object> class ListItr { public: ListItr( ) : current( 0 ) { } bool isPastEnd( ) const {return current == 0; } void advance( ){ if( !isPastEnd( ) ) current = List<Object>::cursorSpace[ current ].next; } const Object & retrieve( ) const { if( isPastEnd( ) ) throw BadIterator( ); return List<Object>::cursorSpace[ current ].element; } private: int current; // Current position friend class List<Object>; ListItr( int theNode ) : current( theNode ) { } };
  • 41. 41 Class skeleton for cursor-based List template <class Object> class ListItr; // Incomplete declaration. template <class Object> class List { public: List( ); List( const List & rhs ); ~List( ); bool isEmpty( ) const; void makeEmpty( ); ListItr<Object> zeroth( ) const; ListItr<Object> first( ) const; void insert( const Object & x, const ListItr<Object> & p ); ListItr<Object> find( const Object & x ) const; ListItr<Object> findPrevious( const Object & x ) const; void remove( const Object & x );
  • 42. 42 Class skeleton for cursor-based List public: struct CursorNode { CursorNode( ) : next( 0 ) { } private: CursorNode( const Object & theElement, int n ) : element( theElement ), next( n ) {} Object element; int next; friend class List<Object>; friend class ListItr<Object>; }; const List & operator=( const List & rhs );
  • 43. 43 Class skeleton for cursor-based List private: int header; static vector<CursorNode> cursorSpace; static void initializeCursorSpace( ); static int alloc( ); static void free( int p ); friend class ListItr<Object>; };
  • 44. 44 cursorSpace initialization /* Routine to initialize the cursorSpace. */ template <class Object> void List<Object>::initializeCursorSpace( ) { static int cursorSpaceIsInitialized = false; if( !cursorSpaceIsInitialized ) { cursorSpace.resize( 100 ); for( int i = 0; i < cursorSpace.size( ); i++ ) cursorSpace[ i ].next = i + 1; cursorSpace[ cursorSpace.size( ) - 1 ].next = 0; cursorSpaceIsInitialized = true; } }
  • 45. 45 Routines : alloc and free /* Allocate a CursorNode template <class Object> int List<Object>::alloc( ) { int p = cursorSpace[ 0 ].next; cursorSpace[ 0 ].next = cursorSpace[ p ].next; return p; } /* Free a CursorNode template <class Object> void List<Object>::free( int p ) { cursorSpace[ p ].next = cursorSpace[ 0 ].next; cursorSpace[ 0 ].next = p; }
  • 46. 46 Short routines for cursor-based lists /* Construct the list template <class Object> List<Object>::List( ) { initializeCursorSpace( ); header = alloc( ); cursorSpace[ header ].next = 0; } /* Destroy the list template <class Object> List<Object>::~List( ) { makeEmpty( ); free( header ); }
  • 47. 47 Short routines for cursor-based lists /* Test if the list is logically empty. return true if empty template <class Object> bool List<Object>::isEmpty( ) const { return cursorSpace[ header ].next == 0; } /* Return an iterator representing the first node in the list. This operation is valid for empty lists. template <class Object> ListItr<Object> List<Object>::first( ) const { return ListItr<Object>( cursorSpace[ header ].next ); }
  • 48. 48 find routine - cursor implementation /*Return iterator corresponding to the first node containing an item x. Iterator isPastEnd if item is not found. template <class Object> ListItr<Object> List<Object>::find( const Object & x ) const { int itr = cursorSpace[ header ].next; while( itr != 0 && cursorSpace[ itr ].element != x ) itr = cursorSpace[ itr ].next; return ListItr<Object>( itr ); }
  • 49. 49 insertion routine-cursor implementation /* Insert item x after p. template <class Object> void List<Object>::insert(const Object & x,const ListItr<Object> & p) { if( p.current != 0 ) { int pos = p.current; int tmp = alloc( ); cursorSpace[ tmp ] = CursorNode( x, cursorSpace[ pos ].next ); cursorSpace[ pos ].next = tmp; } }
  • 50. 50 deletion routine - cursor implementation /* Remove the first occurrence of an item x. template <class Object> void List<Object>::remove( const Object & x ) { ListItr<Object> p = findPrevious( x ); int pos = p.current; if( cursorSpace[ pos ].next != 0 ) { int tmp = cursorSpace[ pos ].next; cursorSpace[ pos ].next = cursorSpace[ tmp ].next; free ( tmp ); } }