Advertisement

deleting an entire linked list

Started by July 06, 2000 09:17 PM
0 comments, last by dj9781 24 years, 5 months ago
Here's my prob: I have a linked list of names on a waiting list inside a linked list of videos and when my prog is done using them I want to delete the lists. If I just delete the videos list will the waiting list also be deleted? Or do I first have to delete the waiting list then the videos? I wrote a function to do the latter but, a. I dont know if I have to bother deleting the waiting list, and b. I dont get any errors but Im not sure if it's doing what I want it to do. Heres my code:
    
//waiting list definition

typedef struct wait
{
	char lastname[80];
	char firstname[80];
	
	struct wait *next;	// link to next video

}wait_t;


// video definition

typedef struct video
{
	int have;
	int want;
	char title[80];
	wait_t *waithead;    //link to head of waiting list


	struct video *next;	 // link to next video

} video_t;



void deleteInventory(video_t **head) 
{
		
	video_t *temp;
	wait_t  *temp2;

	temp = *head;
	temp2 = temp->waithead;

	while(*head) 
	{

		if(!temp->waithead) //there is no waiting list for video so delete video

		{
			*head = temp->next;		
			delete temp;
			temp = *head;
		}
		else//the video has a waiting list so first delete the list

		{
			while(temp2) 
			{
				temp2 = temp->waithead->next;
				delete temp->waithead;
				temp->waithead = temp2;
			}
			
			*head = temp->next;		
			delete temp;
			temp = *head;
		}


	}

	*head = NULL;
	temp = NULL;
}
    
Edited by - dj9781 on 7/6/00 9:20:39 PM
To avoid a memory leak, you''ll have to delete the links of the waithead list in a similar fashion, eg:

    ...  while(temp2)   {    temp2 = temp->waithead->next;    // call a routine to delete the link (similar to this one)    deleteWaithead(temp->waithead);    delete temp->waithead;    temp->waithead = temp2;  }...[/source]However, since you are already using C++, I would suggest making your life easier and just doing the link deletion within the class itself, eg:[source]struct link1{  int data1;  link1 *next;  link1() {    next = NULL;  }  ~link1() {    delete next; // will recursively delete the connections,                 // assuming a singly-linked list  }};struct link2{  int data2;  link1 *wait;  link2 *next;  link2() {    wait = NULL;    next = NULL;  }  ~link2() {    delete wait;    delete next;  }};    


And you could make member functions for the various routines to add and remove links. Does this make sense?

This topic is closed to new replies.

Advertisement