Re: Link List
Jack wrote:
Ok, so below is a little code I just wrote up. I am wondering when I
delete temp2, does it actually delete all the data that temp2 is
pointing to or not?
#include <iostream>
using namespace std;
Even though it is a struct, you should
add a constructor so that you can help
debug stuff
struct myStruct {
myStruct() : Id(-1), visited(false), next(NULL) {}
int Id;
bool visited;
myStruct *next;
};
int main (){
myStruct *head = NULL;
myStruct *temp2 = NULL;
myStruct *temp = new myStruct;
head = temp;
cout << "Now creating the links\n";
for (int i = 0; i < 10; i++){
temp->Id = i;
temp->visited = false;
cout << temp->Id << " ";
temp2 = temp;
temp = new myStruct;
temp2->next = temp;
}
I think that at the end of this look you have 11
nodes: 0 to 9 and 1 containing garbage as an id and
next points to never-never land since you do not have
a constructor. Add the constructor and make sure you
only create 10 nodes. (that is left to you as an
exercise.)
//LETS SAY WE WANT TO DELETE ITEM NUMBER 6
temp = head;
cout << "\nNow deleting the link 6\n";
while ( (temp->next != NULL) && (temp->Id !=5) ){
cout << temp->Id << " ";
temp = temp->next;
}
temp2 = temp->next;
temp->next = temp->next->next;
delete (temp2); //DOES THIS DELETE ALL THE DATA THAT
TEMP2 IS POINTING TO?
Yes, you are doing the unlinking and deletion correctly here.
cout << "\nNow reprinting... \n";
temp = head;
while(temp->next != NULL){
cout << temp->Id << " ";
temp = temp->next;
}
This really should core dump right here since your last node
points to something other than NULL (most likely).
Good Luck with your project!
return 0;
}