SlideShare a Scribd company logo
1 of 50
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

Graph traversals in Data Structures
Graph traversals in Data StructuresGraph traversals in Data Structures
Graph traversals in Data StructuresAnandhasilambarasan D
 
Graphs bfs dfs
Graphs bfs dfsGraphs bfs dfs
Graphs bfs dfsJaya Gautam
 
Data Structures (CS8391)
Data Structures (CS8391)Data Structures (CS8391)
Data Structures (CS8391)Elavarasi K
 
Analysis of algorithm
Analysis of algorithmAnalysis of algorithm
Analysis of algorithmRajendra Dangwal
 
Bubble sort
Bubble sortBubble sort
Bubble sortManek Ar
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data StructureMeghaj Mallick
 
Dinive conquer algorithm
Dinive conquer algorithmDinive conquer algorithm
Dinive conquer algorithmMohd Arif
 
Abstract Data Types
Abstract Data TypesAbstract Data Types
Abstract Data TypeskarthikeyanC40
 
Array data structure
Array data structureArray data structure
Array data structuremaamir farooq
 
1.8 splay tree
1.8 splay tree 1.8 splay tree
1.8 splay tree Krish_ver2
 
Data Structures and Algorithm Analysis
Data Structures  and  Algorithm AnalysisData Structures  and  Algorithm Analysis
Data Structures and Algorithm AnalysisMary Margarat
 
Breadth First Search & Depth First Search
Breadth First Search & Depth First SearchBreadth First Search & Depth First Search
Breadth First Search & Depth First SearchKevin Jadiya
 
Hash table
Hash tableHash table
Hash tableVu Tran
 

What's hot (20)

Graph traversals in Data Structures
Graph traversals in Data StructuresGraph traversals in Data Structures
Graph traversals in Data Structures
 
Graphs bfs dfs
Graphs bfs dfsGraphs bfs dfs
Graphs bfs dfs
 
Single linked list
Single linked listSingle linked list
Single linked list
 
stack presentation
stack presentationstack presentation
stack presentation
 
Sorting
SortingSorting
Sorting
 
Data Structures (CS8391)
Data Structures (CS8391)Data Structures (CS8391)
Data Structures (CS8391)
 
Linear Search Presentation
Linear Search PresentationLinear Search Presentation
Linear Search Presentation
 
Analysis of algorithm
Analysis of algorithmAnalysis of algorithm
Analysis of algorithm
 
Dijkstra
DijkstraDijkstra
Dijkstra
 
Bubble sort
Bubble sortBubble sort
Bubble sort
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data Structure
 
Dinive conquer algorithm
Dinive conquer algorithmDinive conquer algorithm
Dinive conquer algorithm
 
Abstract Data Types
Abstract Data TypesAbstract Data Types
Abstract Data Types
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
Linked lists
Linked listsLinked lists
Linked lists
 
Array data structure
Array data structureArray data structure
Array data structure
 
1.8 splay tree
1.8 splay tree 1.8 splay tree
1.8 splay tree
 
Data Structures and Algorithm Analysis
Data Structures  and  Algorithm AnalysisData Structures  and  Algorithm Analysis
Data Structures and Algorithm Analysis
 
Breadth First Search & Depth First Search
Breadth First Search & Depth First SearchBreadth First Search & Depth First Search
Breadth First Search & Depth First Search
 
Hash table
Hash tableHash table
Hash table
 

Viewers also liked

Cursor implementation
Cursor implementationCursor implementation
Cursor implementationvicky201
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsHarry Potter
 
358 33 powerpoint-slides_8-linked-lists_chapter-8
358 33 powerpoint-slides_8-linked-lists_chapter-8358 33 powerpoint-slides_8-linked-lists_chapter-8
358 33 powerpoint-slides_8-linked-lists_chapter-8sumitbardhan
 
data structure
data structuredata structure
data structurehashim102
 
Data structures and algorithms made easy
Data structures and algorithms made easyData structures and algorithms made easy
Data structures and algorithms made easyCareerMonk Publications
 
Introduction of data structure
Introduction of data structureIntroduction of data structure
Introduction of data structureeShikshak
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)Olve Maudal
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by ExampleOlve Maudal
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsJulie Iskander
 
Linked list
Linked listLinked list
Linked listakshat360
 
TDD in C - Recently Used List Kata
TDD in C - Recently Used List KataTDD in C - Recently Used List Kata
TDD in C - Recently Used List KataOlve Maudal
 

Viewers also liked (15)

Cursor implementation
Cursor implementationCursor implementation
Cursor implementation
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Linked lists
Linked listsLinked lists
Linked lists
 
358 33 powerpoint-slides_8-linked-lists_chapter-8
358 33 powerpoint-slides_8-linked-lists_chapter-8358 33 powerpoint-slides_8-linked-lists_chapter-8
358 33 powerpoint-slides_8-linked-lists_chapter-8
 
data structure
data structuredata structure
data structure
 
Data structures and algorithms made easy
Data structures and algorithms made easyData structures and algorithms made easy
Data structures and algorithms made easy
 
Introduction of data structure
Introduction of data structureIntroduction of data structure
Introduction of data structure
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
 
linked list
linked list linked list
linked list
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
How A Compiler Works: GNU Toolchain
How A Compiler Works: GNU ToolchainHow A Compiler Works: GNU Toolchain
How A Compiler Works: GNU Toolchain
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Linked list
Linked listLinked list
Linked list
 
TDD in C - Recently Used List Kata
TDD in C - Recently Used List KataTDD in C - Recently Used List Kata
TDD in C - Recently Used List Kata
 
Deep C
Deep CDeep C
Deep C
 

Similar to Data structures & algorithms lecture 3

List,Stacks and Queues.pptx
List,Stacks and Queues.pptxList,Stacks and Queues.pptx
List,Stacks and Queues.pptxUmatulSaboohSaleem1
 
Chapter 5 ds
Chapter 5 dsChapter 5 ds
Chapter 5 dsHanif Durad
 
12888239 (2).ppt
12888239 (2).ppt12888239 (2).ppt
12888239 (2).pptSrinivasanCSE
 
Array linked list.ppt
Array  linked list.pptArray  linked list.ppt
Array linked list.pptWaf1231
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringRAJASEKHARV8
 
General Data structures
General Data structuresGeneral Data structures
General Data structuresYoussef Elsalhawy
 
1 list datastructures
1 list datastructures1 list datastructures
1 list datastructuresNguync91368
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks QueuesIntro C# Book
 
oop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionoop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionssuseredfbe9
 
Adt of lists
Adt of listsAdt of lists
Adt of listsNivegeetha
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueRai University
 

Similar to Data structures & algorithms lecture 3 (20)

List,Stacks and Queues.pptx
List,Stacks and Queues.pptxList,Stacks and Queues.pptx
List,Stacks and Queues.pptx
 
Chapter 5 ds
Chapter 5 dsChapter 5 ds
Chapter 5 ds
 
12888239 (2).ppt
12888239 (2).ppt12888239 (2).ppt
12888239 (2).ppt
 
Array linked list.ppt
Array  linked list.pptArray  linked list.ppt
Array linked list.ppt
 
Lists
ListsLists
Lists
 
List
ListList
List
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and Engineering
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 
General Data structures
General Data structuresGeneral Data structures
General Data structures
 
03-Lists.ppt
03-Lists.ppt03-Lists.ppt
03-Lists.ppt
 
3.ppt
3.ppt3.ppt
3.ppt
 
3.ppt
3.ppt3.ppt
3.ppt
 
1 list datastructures
1 list datastructures1 list datastructures
1 list datastructures
 
javacollections.pdf
javacollections.pdfjavacollections.pdf
javacollections.pdf
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
lec4.ppt
lec4.pptlec4.ppt
lec4.ppt
 
oop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionoop lecture framework,list,maps,collection
oop lecture framework,list,maps,collection
 
Adt of lists
Adt of listsAdt of lists
Adt of lists
 
Collections and generics
Collections and genericsCollections and generics
Collections and generics
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queue
 

More from Poojith Chowdhary

Implementation of MIS and its methods
Implementation of MIS and its methodsImplementation of MIS and its methods
Implementation of MIS and its methodsPoojith Chowdhary
 
THE LIGHT EMITTING DIODE
THE LIGHT EMITTING DIODETHE LIGHT EMITTING DIODE
THE LIGHT EMITTING DIODEPoojith Chowdhary
 
The science of thought
The science of thoughtThe science of thought
The science of thoughtPoojith Chowdhary
 
Child prodigy,savant and late boomers
Child prodigy,savant and late boomersChild prodigy,savant and late boomers
Child prodigy,savant and late boomersPoojith Chowdhary
 
Us wireless cable television
Us wireless cable televisionUs wireless cable television
Us wireless cable televisionPoojith Chowdhary
 
1116297 634468886714442500
1116297 6344688867144425001116297 634468886714442500
1116297 634468886714442500Poojith Chowdhary
 
The new seven wonders of the world
The new seven wonders of the worldThe new seven wonders of the world
The new seven wonders of the worldPoojith Chowdhary
 
The new seven wonders of the world
The new seven wonders of the worldThe new seven wonders of the world
The new seven wonders of the worldPoojith Chowdhary
 

More from Poojith Chowdhary (20)

Voltage multiplier
Voltage multiplierVoltage multiplier
Voltage multiplier
 
Implementation of MIS and its methods
Implementation of MIS and its methodsImplementation of MIS and its methods
Implementation of MIS and its methods
 
THE LIGHT EMITTING DIODE
THE LIGHT EMITTING DIODETHE LIGHT EMITTING DIODE
THE LIGHT EMITTING DIODE
 
High k dielectric
High k dielectricHigh k dielectric
High k dielectric
 
The science of thought
The science of thoughtThe science of thought
The science of thought
 
Child prodigy,savant and late boomers
Child prodigy,savant and late boomersChild prodigy,savant and late boomers
Child prodigy,savant and late boomers
 
Us wireless cable television
Us wireless cable televisionUs wireless cable television
Us wireless cable television
 
1116297 634468886714442500
1116297 6344688867144425001116297 634468886714442500
1116297 634468886714442500
 
Photo transistors
Photo transistorsPhoto transistors
Photo transistors
 
8086 micro processor
8086 micro processor8086 micro processor
8086 micro processor
 
8051 micro controller
8051 micro controller8051 micro controller
8051 micro controller
 
8085 micro processor
8085 micro processor8085 micro processor
8085 micro processor
 
Quantum mechanics
Quantum mechanicsQuantum mechanics
Quantum mechanics
 
Function generator
Function generatorFunction generator
Function generator
 
Resistors
ResistorsResistors
Resistors
 
The new seven wonders of the world
The new seven wonders of the worldThe new seven wonders of the world
The new seven wonders of the world
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
The new seven wonders of the world
The new seven wonders of the worldThe new seven wonders of the world
The new seven wonders of the world
 
Animal lifecycles
Animal lifecyclesAnimal lifecycles
Animal lifecycles
 
Resistors
ResistorsResistors
Resistors
 

Recently uploaded

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Dr. Mazin Mohamed alkathiri
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Recently uploaded (20)

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

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 ); } }