Need help writing destructor's for linked list

I am having difficulty writing destructors for my node and list classes, all of my research hasn't provided me with enough details. Any help would be appreciated. Here is my header oode. Also a note, my node class cannot delete the entire list.

List Header
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class List
 {
 private:
	 // Variable Name: numNodes
	 // Purpose: Variable that contains the number of nodes
	 // Parameters: None
	 // Returns: None
	 // Pre-conditions: Must be of type int
	 // Post-conditions: None
	 int numNodes;

	 // Variable Name: next
	 // Purpose: Points to the first node
	 // Parameters: None
	 // Returns: None
	 Node* firstNode;

	 // Variable Name: next
	 // Purpose: Points to the last node
	 // Parameters: None
	 // Returns: None
	 Node* lastNode;

 public:
	 // Default Constructor Name: List
	 // Purpose: Default constructor to initialize
	 // Parameters: None
	 // Returns: None
	 List();

	 ~List();

	 // Function Name: push_back
	 // Purpose: Take the node and place it at the end of the list
	 // Parameters: Node pointer
	 // Returns: None
	 // Pre-conditions: Node cannot be NULL
	 // Post-conditions: None
	 void push_back(Node*);

	 // Function Name: push_front
	 // Purpose: Take the node and place it at the front of the list
	 // Parameters: Node pointer
	 // Returns: None
	 // Pre-conditions: Node cannot be NULL
	 // Post-conditions: None
	 void push_front(Node*);

	 // Function Name: pop_back
	 // Purpose: Removes last node from list
	 // Parameters: None
	 // Returns: A pointer to this node
	 // Pre-conditions: None
	 // Post-conditions: None
	 Node* pop_back();

	 // Function Name: pop_front
	 // Purpose: Removes first node from list
	 // Parameters: None
	 // Returns: A pointer to this node
	 // Pre-conditions: None
	 // Post-conditions: None
	 Node* pop_front();

	 // Function Name: getFirstNode
	 // Purpose: To get the first node
	 // Parameters: None
	 // Returns: A pointer to the first node
	 // Pre-conditions: None
	 // Post-conditions: None
	 Node* getFirstNode();

	 // Function Name: getLastNode
	 // Purpose: To get the last node
	 // Parameters: None
	 // Returns: A pointer to the last node
	 // Pre-conditions: None
	 // Post-conditions: None
	 Node* getLastNode();
 };


Node Header
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Node
 {
 private:
	 // Variable Name: next
	 // Purpose: Points to the next node
	 // Parameters: None
	 // Returns: None
	 Node* next;

	 // Varible Name: CarPart
	 CarPart* carPart;

 public:
	 // Default Constructor Name: Node
	 // Purpose: Default constructor to initialize
	 // Parameters: None
	 // Returns: None
	 Node();

	 // Parameterized Constructor Name: Node
	 // Purpose: Parameterized constructor to initialize
	 // Parameters: A string value
	 // Returns: None
	 Node(std::string);

	 //Destructor
	 //Purpose:Deletes any dynamically allocated storage
	 //Parameters: None
	 //Returns: None
	 ~Node();

	 // Getter Name: getNext
	 // Purpose: Initialize data
	 // Parameters: None
	 // Returns: None
	 Node* getNext();

	 // Setter Name: setNext
	 // Purpose: Initialize data
	 // Parameters: A pointer to next node
	 // Returns: None
	 void setNext(Node*);
 };


CarPart Header

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class CarPart
{

private:
	// Variable Name: partNumber
	// Purpose: Variable that contains a unique identifier
	// Parameters: None
	// Returns: None
	// Pre-conditions: Must be of type string
	// Post-conditions: None
	std::string partNumber;

	// Variable Name: partDescription
	// Purpose: Variable that contains the parts description
	// Parameters: None
	// Returns: None
	// Pre-conditions: Must be of type string
	// Post-conditions: None
	std::string partDescription;

	// Variable Name: price
	// Purpose: Variable that contains price
	// Parameters: None
	// Returns: None
	// Pre-conditions: Must be of type double
	// Post-conditions: None
	double price;

public:
	// Default Constructor Name: CarPart
	// Purpose: Default constructor to initialize
	// Parameters: None
	// Returns: None
	 CarPart();

	 // Parameterized Constructor Name: CarPart
	 // Purpose: Parameterized constructor to initialize data types
	 // Parameters: A string value, a string value, and a double value
	 // Returns: None
	 CarPart(std::string partNum, std::string partDesc, double partPrice);

	 // Function Name: getPartNumber
	 // Purpose: To get the number for the part
	 // Parameters: None
	 // Returns: None
	 // Pre-conditions: Part number cannot be NULL
	 // Post-conditions: None
	 std::string getPartNumber() const;

	 // Setter Name: setPartNumber
	 // Purpose: Initialize data
	 // Parameters: A string object
	 // Returns: None
	 void setPartNumber(std::string);

	 // Function Name: getDescription
	 // Purpose: To get the description for the part
	 // Parameters: None
	 // Returns: None
	 // Pre-conditions: Description cannot be empty
	 // Post-conditions: None
	 std::string getDescription() const;

	 // Setter Name: setDescription
	 // Purpose: Initialize data
	 // Parameters: A string object
	 // Returns: None
	 void setDescription(std::string);

	 // Function Name: getPrice
	 // Purpose: To get the price for the part
	 // Parameters: None
	 // Returns: None
	 // Pre-conditions: Node cannot be NULL
	 // Post-conditions: None
	 double getPrice() const;

	 // Setter Name: setPrice
	 // Purpose: Initialize data
	 // Parameters: A double object
	 // Returns: None
	 void setPrice(double);
};
Last edited on
closed account (SECMoG1T)
You'll need to write destructors for both your node and list classes coz both seem to use dynamic memory.

Your node destructor should free the memory allocated to carparts, your list destructor should free all dynamically allocated nodes but i got one question is your CarPart* carPart another list or a dynamic array, if it's a dynamic array you'll just delete the array , else you'll just use a similar procedure to that of freeing your linked list.

For your list destructor , you just need a few steps to get it working.

1. Create a temporal pointer pointing to your firstnode.
2. Alter your firstnode to point to the next node;
3. Delete the temporal pointer ans set it to nullptr.
4. Repeat the process while the list is not empty.
This is the clip from the book, hopefully that answers your question. I just wrote what was required as the data member.

The Node Class: In this project your Node class will include

A Node* that will be used to point to the next Node in the List.
A CarPart* that will point to a CarPart object.
Write the necessary default and parameterized constructors and getters and setters for your Node class. You will also need a destructor in your Node class. Be careful, you do not want your Node destructor to cause the entire list to be deleted.

The List Class: Implement a List class with the following data members:

A Node* that points to the first Node in the List.
A Node* that points to the last Node in the List.
An integer that contains the number of Nodes in the List.
Your List class should have the following functions:

A default constructor that creates an empty List object.
A destructor
A push_front function that takes a Node* as a parameter and adds the node pointed to by the pointer to the front of the list.
A pop_front function that removes the first node from the list, and returns a pointer to this node. Important, do not delete the node in this function. Simply unlink it from the list.
A getFirst function that returns a pointer to the first node in the list.
The printList Function:You will also need to create a stand-alone function and add it to the driver that has been provided for you. Your printList function takes a LinkedList object as it's parameter and prints out the data for each CarPart object pointed to by the Node objects in the list. The output for a CarPart object should look something like

X20345-t Radiator Cap $3.95

i.e. the part number followed by the description and the price. The driver code that has been provided includes a function prologue, a function prototype, and a stub for this function. You just need to fill in the code that implements the function.

The Driver: Build your program with the driver that has been provided.
Here is what I have tried for both the node and the list, I am getting an error on line 8 of the list saying not declared when I use the next function, I am not calling it the way it should be. How would your correct them.
Node Implementation
1
2
3
4
5
6
7
Node::~Node()
{
	if (carPart != NULL)
	{
		delete carPart;
	}
}

List Implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
List::~List()
{
	Node* tempPtr = this->firstNode;
	Node* current = NULL;
	while (firstNode)
	{
		current = firstNode;
		firstNode = firstNode->next;
		delete firstNode;
	}
	firstNode = NULL;
	lastNode = NULL;
}
Last edited on
closed account (SECMoG1T)
Okay am not pretty sure what your node class carPart* really is, if it just points to a single CarPart object then your node class destructor does the right thing.

Your second destructor, on my first post I gave you a routine you could apply but might be you missed that, no big deal I can point you in the right direction again.

You might consider creating a private helping function in your list class, these function should be returning a bool indicating whether your list is empty ,
i.e. firstnode==nullptr&&lastnode==nullptr, such a ffunction will be very handy when working on your linked list.

The error am spotting on your list destructor is outlined below.

- your destructor is causing mem leak ,but you are almost on track.
- immediately you called delete on your first iteration inside the loop, firstnode Will be pointing to an
invalid address , on your second iteration calling firstNode = firstNode->next; will be
illegal coz the invalid address will not have a member called "next" .
- the other part of your list will be left hanging in unreacherable memory.


Please reference the routine I provided on the first post and your destructor will work, if you get a problem post your code and will it out.




I did not see that post so you will have to help me through this, I don't understand all of the requirements, here is what I have and not sure what to put for #2 or #4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
List::~List()
{
	//1. Create a temporal pointer pointing to your firstnode.
	Node* tempPtr = firstNode;
	//2. Alter your firstnode to point to the next node;
	firstNode = ;
	//3. Delete the temporal pointer ans set it to nullptr.
	delete tempPtr;
	tempPtr = nullptr;
	//4. Repeat the process while the list is not empty.
	while (numNodes != NULL)
	{

	}
}
Last edited on
closed account (SECMoG1T)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
List::~List()
 { 	
      while (firstNode!=nullptr&&lastnode!=nullptr)
     {
     //1. Create a temporal pointer pointing to your firstnode. 	
        Node* tempPtr = firstNode; 	
    //2. Alter your firstnode to point to the next node; 	
      firstNode =firstNode-> next ; 	
    //3. Delete the temporal pointer ans set it to nullptr. 	
      delete tempPtr; 	
      tempPtr = nullptr; 	
    //4. Repeat the process while the list is not empty. 	
    }
    firstNode=nullptr; 
 }


Something like that;
So when I put that into my implementation file, the line 8 gives me an error. Do I have to change my header file so that is accessible? Or can I call getNext();
Last edited on
closed account (SECMoG1T)
Ooh you just missed something and your loop definetly doesn't accomplish what you intend.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 List::~List()///by this I assume your lastnode-> next is always equal to nullptr
  { 	
    Node* tempPtr = firstNode;  	
    firstNode = firstNode-> next;///  here you are defining a member  function you dont need to use getters
                                                     /// they just induce unnecessary overhead
   while (firstNode!=NULL) 	
     { 		
        delete tempPtr;
        --numnodes;
        tempPtr = firstNode;
        firstNode=firstNode-> next;
     } 
   ///when you get here firstNode=NULL, lastnode= invalid address;
     lastnode=NULL;
  }
Next is still undefined, how do I fix this? Thanks to you for all your help
closed account (SECMoG1T)
Please post the code you are getting an error on
1
2
3
4
5
6
7
8
9
10
11
12
13
List::~List()
{
	Node* tempPtr = firstNode;
	firstNode = firstNode->next;
	while (firstNode != NULL)
	{
		delete tempPtr;
		--numNodes;
		tempPtr = firstNode;
		firstNode = firstNode->next;
	}
	lastNode = NULL;
}


Error is occurring on line 4 and 10 saying 'next' is un-accessible from line 8 of my header above
Last edited on
closed account (SECMoG1T)
Ooh sorry for that I see I dint make sense somwhere, the node ain't a friend to your list class, here is the solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 List::~List ()
  {
    Node* tempPtr=firstNode;
    firstNode=firstNode-> getNext ();///sorry for that
   
     while (firstNode! =NULL)
       {
           delete tempPtr;
           --numnodes; 
           tempPtr=firstNode; 
           firstNode=firstNode-> getNext ();
       }
    lastnode=NULL;
  }

 


[/code]
Awesome! thank you for your help @andy1992
Topic archived. No new replies allowed.