Lecture 9 Linked Lists - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture09-LinkedLists.pdf ·...
Transcript of Lecture 9 Linked Lists - CCVCLvisionlab.engr.ccny.cuny.edu/~fhu/Lecture09-LinkedLists.pdf ·...
CSC212 Data Structure
- Section FG
Lecture9LinkedLists
Instructor:FengHUDepartmentofComputerScience
CityCollegeofNewYork
Motivation
• Inasequenceusinganarray,insertinganewitemneedstomoveothersback...
10 20 30 ? ?
18
Motivation
• Inasequenceusinganarray,insertinganewitemneedstomoveothersback...
10 20 20 30 ?
18
Motivation
• Inasequenceusinganarray,insertinganewitemneedstomoveothersback...
• SotheBig-OoftheinsertisO(n)
10 18 20 30 ?
Motivation
• Howcanweinsertanewitemwithoutmovingothers?
10 20 30 ? ?
18
We need a new data structure
Motivation
• Howcanweinsertanewitemwithoutmovingothers?
18
??302010
break an array into a linked chain...
Motivation
• Howcanweinsertanewitemwithoutmovingothers?
18
??302010
and then put the new item into the chain
Motivation
• Howcanweinsertanewitemwithoutmovingothers?
18
??302010
But the links (->) need some way to build up
LinkedListsinAction
•Chapter5introducestheoften-useddatastructureoflinkedlists.
• Thispresentationshowshowtoimplementthemostcommonoperationsonlinkedlists.
CHAPTER 5Data Structures and Other Objects
DeclarationsforLinkedLists
• Eachnode inthelinkedlistisaclass,asshownhere.
data
link
10
data
link
15
data
link
7
null
class node{public:
typedef int value_type;...
private:value_type data;node *link;
};
data
link
7
DeclarationsforLinkedLists
• Thedataportionofeachnodeisatypecalledvalue_type,definedbyatypedef.
link
null
data
link
15
data10
class node{public:
typedef int value_type;...
private:value_type data;node *link;
};
DeclarationsforLinkedLists
• Eachnodealsocontainsalinkfieldwhichisapointertoanothernode.
data15
data7
data10
link
linknull
link
class node{public:
typedef int value_type;...
private:value_type data;node *link;
};
DeclarationsforLinkedLists
• Aprogramcankeeptrackofthefirstnodebyusingapointervariablesuchashead_ptr inthisexample.
• Noticethathead_ptr itselfisnotanode-- itisapointertoanode.
data
link
10
data
link
15
data
link
7
nullhead_ptr
node * head_ptr;
DeclarationsforLinkedLists
• Aprogramcanalsokeeptrackofthelastnodebyusingapointervariablesuchastail_ptr inthisexample.
• Noticethattail_ptr itselfisnotanode-- itisapointertoanode.
data
link
10
data
link
15
data
link
7
nullhead_ptr
node * head_ptr;node * tail_ptr; tail_ptr
DeclarationsforLinkedLists
• Aprogramcankeeptrackofthefirstandthelastnodesbyusingpointervariablessuchashead_ptr,tail_ptr.
• Noticethatneitherhead_ptrnortail_ptrisanode-- itisapointertoanode.
• Foranemptylist,null isstoredinboththeheadandthetailpointers.
head_ptrnull
tail_ptrnull
node * head_ptr;node * tail_ptr;head_ptr = NULL;tail_ptr = NULL;// NULL can be used for any pointers!
TheComplete node ClassDefinition
• Thenodeclassisfundamentaltolinkedlists• Theprivatemembervariables
• data:avalue_typevariable• link:apointertothenextnode
• Thememberfunctionsinclude:• Aconstructor• Setdataandsetlink• Retrievedataandretrievelink
TheComplete node ClassDefinition
• Thenodeclassisfundamentaltolinkedlists• Theprivatemembervariables
• data_field• link_field
• Thememberfunctionsinclude:• Aconstructor• Setdataandsetlink• Retrievedataandretrievelink
class node{public:
// TYPEDEFtypedef double value_type;
// CONSTRUCTORnode(
const value_type& init_data = value_type( ),node* init_link = NULL
){ data = init_data; link = init_link; }
// Member functions to set the data and link fields:void set_data(const value_type& new_data) { data = new_data; }void set_link(node* new_link) { link = new_link; }
// Constant member function to retrieve the current data:value_type data( ) const { return data; }
// Two slightly different member functions to retrieve// the current link:const node* link( ) const { return link; }node* link( ) { return link;}
private:value_type data;node* link;
};
default argument given by the value_type default constructor
Why TWO? p. 213-4
ASmallQuiz-
• Supposeaaprogramhasbuiltthelinkedlistasshown,andhead_ptrisapointertoanode.
• What is the data type of *head_ptr?• cout << (*head_ptr). data();• cout << head_ptr->data();
data
link
10
data
link
15
data
link
7
nullhead_ptr
LinkedListToolkit
• DesignContainerClassesusingLinkedLists• Theuseofalinked listissimilartoourprevioususeofanarrayinacontainerclass
• Butstoringandretrievingneedsmoreworksincewedonothavethathandyindexing
• =>LinkedListToolbox• usingnodeclass
TheWorkingsoffourfunctions
• Thislecturewillshowfourfunctions:• Computethelengthofalinkedlist(code)• Insertanewnodeatthehead(code)• Insertanodeatanylocation(pseudo-code)• Deleteanodefromthehead(pseudo-code)
•ReadSection5.2forotherfunctionsintheToolbox• willbeusedincontainerclassesbagandsequence
size_t list_length(const node* head_ptr);
LengthofaLinkedList
Wesimplywanttocomputethelength ofthelinkedlist,forexampletheoneshownhere.
Notethatlist_lengthisnotamemberfunctionofthenodeclass
10
15
7
nullhead_ptr
size_t list_length(const node* head_ptr);
Pseudo-codeoflist_length
1. Initializethecount tozero.2. Makecursorpointtoeachnode,
startingatthehead.Eachtimecursorpointstoanewnode,add1tocount.
3. returncount.
10
15
7
nullhead_ptr
count0
size_t list_length(const node* head_ptr);
Pseudo-codeoflist_length
1. Initializethecount tozero.2. Makecursorpointtoeachnode,
startingatthehead.Eachtimecursorpointstoanewnode,add1tocount.
3. returncount.
10
15
7
nullhead_ptr
count1
cursor
size_t list_length(const node* head_ptr);
Pseudo-codeoflist_length
1. Initializethecount tozero.2. Makecursorpointtoeachnode,
startingatthehead.Eachtimecursorpointstoanewnode,add1tocount.
3. returncount.
10
15
7
nullhead_ptr
count2
cursor
size_t list_length(const node* head_ptr);
Pseudo-codeoflist_length
1. Initializethecount tozero.2. Makecursorpointtoeachnode,
startingatthehead.Eachtimecursorpointstoanewnode,add1tocount.
3. returncount.
10
15
7
nullhead_ptr
count3
cursor
size_t list_length(const node* head_ptr);
Pseudo-codeoflist_length
1. Initializethecount tozero.2. Makecursorpointtoeachnode,
startingatthehead.Eachtimecursorpointstoanewnode,add1tocount.
3. returncount.
10
15
7
nullhead_ptr
count3
cursor
size_t list_length(const node* head_ptr){
const node *cursor;size_t count = 0; // step 1for (cursor = head_ptr; cursor != NULL; cursor = cursor->link())
count++; // step 2return count; // step 3
}
Realcodeoflist_length:ListTraverse
1. Initializethecount tozero.2. Eachtimecursor pointstoanew
node,add1tocount.3. returncount.
10
15
7
nullhead_ptrcount
0
cursor
size_t list_length(const node* head_ptr){
const node *cursor;size_t count = 0; // step 1for (cursor = head_ptr; cursor != NULL; cursor = cursor->link())
count++; // step 2return count; // step 3
}
Realcodeoflist_length:ListTraverse
1. Initializethecount tozero.2. Eachtimecursor pointstoanew
node,add1tocount.3. returncount.
10
15
7
nullhead_ptrcount
1
cursor
size_t list_length(const node* head_ptr){
const node *cursor;size_t count = 0; // step 1for (cursor = head_ptr; cursor != NULL; cursor = cursor->link())
count++; // step 2return count; // step 3
}
Realcodeoflist_length:ListTraverse
1. Initializethecount tozero.2. Eachtimecursor pointstoanew
node,add1tocount.3. returncount.
10
15
7
nullhead_ptrcount
2cursor
size_t list_length(const node* head_ptr){
const node *cursor;size_t count = 0; // step 1for (cursor = head_ptr; cursor != NULL; cursor = cursor->link())
count++; // step 2return count; // step 3
}
Realcodeoflist_length:ListTraverse
1. Initializethecount tozero.2. Eachtimecursor pointstoanew
node,add1tocount.3. returncount.
10
15
7
nullhead_ptrcount
3
cursor
size_t list_length(const node* head_ptr){
const node *cursor;size_t count = 0;for (cursor = head_ptr; cursor != NULL; cursor = cursor->link())
count++;return count; // step 3
}
Big-Ooflist_length
Big-O:O(n)iflengthisn10
15
7
nullhead_ptrcount
3
cursor
size_t list_length(const node* head_ptr){
const node *cursor;size_t count = 0;for (cursor = head_ptr; cursor != NULL; cursor = cursor->link())
count++;return count;
}
Islist_lengthworksforanemptylist?
cursor=head_ptr=NULLcount=0
count0
head_ptr
nullcursor
null
TheWorkingsoffourfunctions
• Thislecturewillshowfourfunctions:• Computethelengthofalinkedlist(code)• Insertanewnodeatthehead(code)• Insertanodeatanylocation(pseudo-code)• Deleteanodefromthehead(pseudo-code)
•ReadSection5.2forotherfunctionsintheToolbox• willbeusedincontainerclassesbagandsequence
void list_head_insert(node*& head_ptr, const node::value_type& entry);
InsertinganodeattheHead
Wewanttoaddanewentry,13,tothehead ofthelinkedlistshownhere.
Notethathead_ptrisareferencenodepointer
10
15
7
nullhead_ptr
entry13
InsertingaNodeattheHead
❶ Createanewnode,pointedtobyalocalvariableinsert_ptr.
10
15
7
nullhead_ptr
entry13
insert_ptr
void list_head_insert(node*& head_ptr, const node::value_type& entry);
InsertingaNodeattheHead
❶ insert_ptr = new node;
10
15
7
nullhead_ptr
entry13
insert_ptr
void list_head_insert(node*& head_ptr, const node::value_type& entry);
InsertingaNodeattheHead
❶ insert_ptr = new node;❷ Placethedatainthenewnode'sdata
field.
10
15
7
nullhead_ptr
entry13
insert_ptr13
void list_head_insert(node*& head_ptr, const node::value_type& entry);
InsertingaNodeattheHead
❶ insert_ptr = new node;❷ insert_ptr->data = entry;
What expression appears on the left side of the assignment statement ?
10
15
7
nullhead_ptr
entry13
insert_ptr13
?
void list_head_insert(node*& head_ptr, const node::value_type& entry);
InsertingaNodeattheHead
❶ insert_ptr = new node;❷ insert_ptr->data = entry;
But data is a private variable, so cannot be accessed by a non-member function
10
15
7
nullhead_ptr
entry13
insert_ptr13
void list_head_insert(node*& head_ptr, const node::value_type& entry);
InsertingaNodeattheHead
❶ insert_ptr = new node;❷ insert_ptr->data = entry;
But data is a private variable, so cannot be accessed by a non-member function
10
15
7
nullhead_ptr
entry13
insert_ptr13
void list_head_insert(node*& head_ptr, const node::value_type& entry);
X
InsertingaNodeattheHead
❶ insert_ptr = new node;❷ insert_ptr->set_data(entry);
Instead, Set_data function is used since data_field is a private variable of the node class
10
15
7
nullhead_ptr
entry13
insert_ptr13
void list_head_insert(node*& head_ptr, const node::value_type& entry);
InsertingaNodeattheHead
10
15
7
nullhead_ptr
entry13
insert_ptr13
❶ insert_ptr = new node;❷ insert_ptr->set_data(entry);❸ Connect the new node to the
front of the list.
void list_head_insert(node*& head_ptr, const node::value_type& entry);
InsertingaNodeattheHead
What will be the parameter ?
10
15
7
nullhead_ptr
entry13
insert_ptr13
❶ insert_ptr = new node;❷ insert_ptr->set_data(entry);➌ insert_ptr->set_link(head_ptr);?
void list_head_insert(node*& head_ptr, const node::value_type& entry);
InsertingaNodeattheHead
The new node is linked to the node that head_ptr is pointing to. 10
15
7
nullhead_ptr
entry13
insert_ptr13
❶ insert_ptr = new node;❷ insert_ptr->set_data(entry);➌ insert_ptr->set_link(head_ptr);
void list_head_insert(node*& head_ptr, const node::value_type& entry);
InsertingaNodeattheHead
10
15
7
nullhead_ptr
entry13
insert_ptr13
❶ insert_ptr = new node;❷ insert_ptr->set_data(entry);➌ insert_ptr->set_link(head_ptr);❹ Make the head_ptr point to the new
head of the linked list.
void list_head_insert(node*& head_ptr, const node::value_type& entry);
InsertingaNodeattheHead
10
15
7
nullhead_ptr
entry13
insert_ptr13
❶ insert_ptr = new node;❷ insert_ptr->set_data(entry);➌ insert_ptr->set_link(head_ptr);➍ head_ptr = insert_ptr;
void list_head_insert(node*& head_ptr, const node::value_type& entry);
InsertingaNodeattheHead
❶ insert_ptr = new node;❷ insert_ptr->set_data(entry);➌ insert_ptr->set_link(head_ptr);➍ head_ptr = insert_ptr;
10
15
7
nullhead_ptr
13
When the function returns, thelinked list has a new node at thehead, containing 13.
void list_head_insert(node*& head_ptr, const node::value_type& entry);
void list_head_insert(node*& head_ptr, const node::value_type& entry){
node *insert_ptr;
insert_ptr = new node;insert_ptr->set_data(entry);insert_ptr->set_link(head_ptr);head_ptr = insert_ptr;
}
InsertingaNodeattheHead
Linked List: O(1)
- cmp: Array: O(n)
What is the Big-O of
the head_insert function?
void list_head_insert(node*& head_ptr, const node::value_type& entry){
node *insert_ptr;
insert_ptr = new node;insert_ptr->set_data(entry);insert_ptr->set_link(head_ptr);head_ptr = insert_ptr;
}
InsertingaNodeattheHead
Does the function workcorrectly for the empty
list ?
void list_head_insert(node*& head_ptr, const node::value_type& entry){
node *insert_ptr;
insert_ptr = new node;insert_ptr->set_data(entry);insert_ptr->set_link(head_ptr);head_ptr = insert_ptr;
}
InsertingaNodeattheHead
head_ptrentry13 null
Does the function workcorrectly for the empty
list ?
void list_head_insert(node*& head_ptr, const node::value_type& entry){
node *insert_ptr;
insert_ptr = new node;insert_ptr->set_data(entry);insert_ptr->set_link(head_ptr);head_ptr = insert_ptr;
}
InsertingaNodeattheFront
head_ptrentry13 null
insert_ptr13
void list_head_insert(node*& head_ptr, const node::value_type& entry){
node *insert_ptr;
insert_ptr = new node;insert_ptr->set_data(entry);insert_ptr->set_link(head_ptr);head_ptr = insert_ptr;
}
InsertingaNodeattheHead
head_ptrentry13 null
insert_ptr13
null
void list_head_insert(node*& head_ptr, const node::value_type& entry){
node *insert_ptr;
insert_ptr = new node;insert_ptr->set_data(entry);insert_ptr->set_link(head_ptr);head_ptr = insert_ptr;
}
InsertingaNodeattheHead
head_ptrentry13
insert_ptr13
null
void list_head_insert(node*& head_ptr, const node::value_type& entry){
node *insert_ptr;
insert_ptr = new node;insert_ptr->set_data(entry);insert_ptr->set_link(head_ptr);head_ptr = insert_ptr;
}
InsertingaNodeattheHead
head_ptr
13
null
When the functionreturns, the linked list
has one node,containing 13.
Caution!
•Alwaysmakesurethatyourlinkedlistfunctionsworkcorrectlywithanemptylist.
EMPTY LIST
void list_head_insert(node*& head_ptr, const node::value_type& entry){
node *insert_ptr;
insert_ptr = new node;insert_ptr->set_data(entry);insert_ptr->set_link(head_ptr);head_ptr = insert_ptr;
}
InsertingaNodeattheHead
Q: Can you give an implementation with ONLY a single statement?
void list_head_insert(node*& head_ptr, const node::value_type& entry){
node *insert_ptr;
insert_ptr = new node(entry, head_ptr);
head_ptr = insert_ptr;}
InsertingaNodeattheHead
YES, we can use the constructor with parameters!
void list_head_insert(node*& head_ptr, const node::value_type& entry){
head_ptr = new node(entry, head_ptr);
}
InsertingaNodeattheHead
and assign the return pointer of new directly to the head pointer !
• Break
DeclarationsforLinkedLists
• Eachnodealsocontainsalinkfieldwhichisapointertoanothernode.
data15
data7
data10
link
linknull
link
class node{public:
typedef int value_type;...
private:value_type data;node *link;
};
TheComplete node ClassDefinition
• Thenodeclassisfundamentaltolinkedlists• Theprivatemembervariables
• data_field• link_field
• Thememberfunctionsinclude:• Aconstructor• Setdataandsetlink• Retrievedataandretrievelink
class node{public:
// TYPEDEFtypedef double value_type;
// CONSTRUCTORnode(
const value_type& init_data = value_type( ),node* init_link = NULL
){ data = init_data; link = init_link; }
// Member functions to set the data and link fields:void set_data(const value_type& new_data) { data = new_data; }void set_link(node* new_link) { link = new_link; }
// Constant member function to retrieve the current data:value_type data( ) const { return data; }
// Two slightly different member functions to retrieve// the current link:const node* link( ) const { return link; }node* link( ) { return link;}
private:value_type data;node* link;
};
default argument given by the value_type default constructor
Why TWO? p. 213-4
size_t list_length(const node* head_ptr){
const node *cursor;size_t count = 0;for (cursor = head_ptr; cursor != NULL; cursor = cursor->link())
count++;return count; // step 3
}
Big-Ooflist_length
Big-O:O(n)iflengthisn10
15
7
nullhead_ptrcount
3
cursor
TheWorkingsoffourfunctions
• Thislecturewillshowfourfunctions:• Computethelengthofalinkedlist(code)• Insertanewnodeatthehead(code)• Insertanodeatanylocation(pseudo-code)• Deleteanodefromthehead(pseudo-code)
•ReadSection5.2forotherfunctionsintheToolbox• willbeusedincontainerclassesbagandsequence
PseudocodeforInsertingNodes
• Nodesareofteninsertedatplacesotherthanthefrontofalinkedlist.• Thereisageneralpseudocodethatyoucanfollowforanyinsertion
function...
PseudocodeforInsertingNodes
❶Determinewhetherthenewnodewillbethefirstnodeinthelinkedlist.Ifso,thenthereisonlyonestep:
list_head_insert(head_ptr, entry);
PseudocodeforInsertingNodes
➊Determinewhetherthenewnodewillbethefirstnodeinthelinkedlist.Ifso,thenthereisonlyonestep:
list_head_insert(head_ptr, entry);
PseudocodeforInsertingNodes
❶Determinewhetherthenewnodewillbethefirstnodeinthelinkedlist.Ifso,thenthereisonlyonestep:
list_head_insert(head_ptr, entry);
A pointerto the
head ofthe list
PseudocodeforInsertingNodes
❶Determinewhetherthenewnodewillbethefirstnodeinthelinkedlist.Ifso,thenthereisonlyonestep:
list_head_insert(head_ptr, entry);
PseudocodeforInsertingNodes
❷ Otherwise (if the new node will not be first):❐ Start by setting a pointer named previous_ptr to point to the
node which is just before the new node's position.
PseudocodeforInsertingNodes
15
10
7
nullhead_ptr
❷ Otherwise (if the new node will not be first):❐ Start by setting a pointer named previous_ptr to point to the
node which is just before the new node's position.
In this example, thenew node will bethe second node
previous_ptr
PseudocodeforInsertingNodes
What is the name of this pointer ?
15
10
7
nullhead_ptr
❷ Otherwise (if the new node will not be first):❐ Start by setting a pointer named previous_ptr to point to the
node which is just before the new node's position
Look at the pointerwhich is in the node
*previous_ptrprevious_ptr
PseudocodeforInsertingNodes
Always remember how can you access link
15
10
7
nullhead_ptr
❷ Otherwise (if the new node will not be first):❐ Start by setting a pointer named previous_ptr to point to the
node which is just before the new node's position
This pointer is calledprevious_ptr->link
previous_ptr
PseudocodeforInsertingNodes
15
10
7
nullhead_ptr
➋ Otherwise (if the new node will not be first):❐ Start by setting a pointer named previous_ptr to point to the
node which is just before the new node's position
previous_ptr->linkpoints to the headof a smaller linkedlist, with 10 and 7
previous_ptr
PseudocodeforInsertingNodes
Write one C++ statement which will do the insertion.
15
10
7
nullhead_ptr
❷ Otherwise (if the new node will not be first):❐ Start by setting a pointer named previous_ptr to point to the
node which is just before the new node's position.
The new node mustbe inserted at thehead of this small
linked list.
13
previous_ptr
PseudocodeforInsertingNodes
Write one C++ statement which will do the insertion.
15
10
7
nullhead_ptr
❷ Otherwise (if the new node will not be first):❐ Start by setting a pointer named previous_ptr to point to the
node which is just before the new node's position. 13
previous_ptrlist_head_insert(previous_ptr->link, entry);
X
PseudocodeforInsertingNodes
More precisely, you need to use member function link() , and have three lines of code
15
10
7
nullhead_ptr
❷ Otherwise (if the new node will not be first):❐ Start by setting a pointer named previous_ptr to point to the
node which is just before the new node's position.13
previous_ptr
node *sl_head_ptr;sl_head_ptr = previous_ptr->link();list_head_insert(sl_head_ptr, entry);previous_ptr->set_link(sl_head_ptr);
sl_head_ptr
PseudocodeforInsertingNodes
More precisely, you need to use member function link() , and have three lines of code
15
10
7
nullhead_ptr
❷ Otherwise (if the new node will not be first):❐ Start by setting a pointer named previous_ptr to point to the
node which is just before the new node's position. 13
previous_ptr
node *sl_head_ptr;sl_head_ptr = previous_ptr->link();list_head_insert(sl_head_ptr, entry);previous_ptr->set_link(sl_head_ptr);
sl_head_ptr
PseudocodeforInsertingNodes
More precisely, you need to use member function link() , and have three lines of code
15
10
7
nullhead_ptr
❷ Otherwise (if the new node will not be first):❐ Start by setting a pointer named previous_ptr to point to the
node which is just before the new node's position. 13
previous_ptr
node *sl_head_ptr;sl_head_ptr = previous_ptr->link();list_head_insert(sl_head_ptr, entry);previous_ptr->set_link(sl_head_ptr);
sl_head_ptr
PseudocodeforInsertingNodes
❶Determinewhetherthenewnodewillbethefirstnodeinthelinkedlist.Ifso,thenthereisonlyonestep:
list_head_insert(head_ptr, entry);
❷ Otherwise (if the new node will not be first):❐ Set a pointer named previous_ptr to point to the node
which is just before the new node's position.❐ Do the following :
node *sl_head_ptr;sl_head_ptr = previous_ptr->link(); list_head_insert(sl_head_ptr, entry);previous_ptr->set_link(sl_head_ptr);
PseudocodeforInsertingNodes
• Theprocessofaddinganewnodeinthemiddleofalist(only the step after previous_ptr has been set)canalsobeincorporatedasaseparatefunction.Thisfunctioniscalledlist_insert inthelinkedlisttoolkitofSection5.2.
• Challengeyourself:• Thetextbookactuallygivesyouadifferentimplementation(p235,4linesofcode)
• Canyouimplementlist_insert withjustonelineofcode?• Don’tuselist_head_insert• SeeSelf-TestEx16
TheWorkingsoffourfunctions
• Thislecturewillshowfourfunctions:• Computethelengthofalinkedlist(code)• Insertanewnodeatthehead(code)• Insertanodeatanylocation(pseudo-code)• Deleteanodefromthehead(pseudo-code)
•ReadSection5.2forotherfunctionsintheToolbox• willbeusedincontainerclassesbagandsequence
PseudocodeforRemovingNodes
• Nodesoftenneedtoberemovedfromalinkedlist.• Aswithinsertion,thereisatechniqueforremovinganodefromthe
frontofalist,andatechniqueforremovinganodefromelsewhere.• We’lllookatthepseudocodeforremovinganodefromtheheadofa
linkedlist.
RemovingtheHeadNode
10 15
7
nullhead_ptr
13
❶ Start by setting up a temporary pointer named remove_ptrto the head node.
remove_ptr
RemovingtheHeadNode
10 15
7
nullhead_ptr
13
❶ Set up remove_ptr.❷ head_ptr = remove_ptr->link();
remove_ptr
Draw the change that this statement will make to the linked list.
RemovingtheHeadNode
10 15
7
nullhead_ptr
13
➊ Set up remove_ptr.➋ head_ptr = remove_ptr->link();
remove_ptr
RemovingtheHeadNode
➊ Set up remove_ptr.➋ head_ptr = remove_ptr->link;❸ delete remove_ptr; // Return the node's memory to heap.
10 15
7
nullhead_ptr
13
remove_ptr
RemovingtheHeadNode
Here’s what the linked list looks like after the removal finishes.
10 15
7
nullhead_ptr
Summary
• Itiseasytoinsertanodeatthefrontofalist.• Thelinkedlisttoolkitalsoprovidesafunctionforinsertinganewnodeelsewhere
• Itiseasytoremoveanodeatthefrontofalist.• Thelinkedlisttoolkitalsoprovidesafunctionforremovinganodeelsewhere--youshouldreadaboutthisfunctionandtheotherfunctionsofthetoolkit.
Keypointsyouneedtoknow
• LinkedListToolkitusesthenodeclasswhichhas• setandretrievefunctions
• ThefunctionsintheToolkitarenotmemberfunctionsofthenodeclass• length,insert(2),remove(2),search,locate,copy,...• comparetheirBig-Oswithsimilarfunctionsforanarray
• Theycanbeusedinvariouscontainerclasses,suchasbag,sequence,etc.
Toolkit Code
Homework...
• Self-TestExercises(node)• 1-12
•Readafterclass• LinkedListToolKit (Section5.2)• DoSelf-TestEx13-25
•Readbeforethenextlecture• Section5.3- 5.4
THE END
Presentation copyright 1997, Addison Wesley Longman,For use with Data Structures and Other Objects Using C++by Michael Main and Walter Savitch.
Some artwork in the presentation is used with permission from Presentation Task Force(copyright New Vision Technologies Inc) and Corel Gallery Clipart Catalog (copyrightCorel Corporation, 3G Graphics Inc, Archive Arts, Cartesia Software, Image ClubGraphics Inc, One Mile Up Inc, TechPool Studios, Totem Graphics Inc).
Students and instructors who use Data Structures and Other Objects Using C++ are welcometo use this presentation however they see fit, so long as this copyright notice remainsintact.