Here is the ListNode struct that is being used throughout this question
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
In each iteration of a loop I have to create a new linked list node.
If I do this in the body of the loop it works:
// t is the linked list: I'm adding a node with a val of currentVal,
// and a next entry of nullptr (you can see the definition of ListNode above)
t->next = new ListNode(currentVal);
But I'm thinking about the whole "avoid using new" issue (for the sake of avoiding memory leaks). Because of that, I have in mind doing this instead:
// t is the linked list: I'm trying to add a node with a val of currentVal,
// and a next entry of nullptr
ListNode listNode(currentVal);
t->next = &listNode;
The problem with the second method is that, starting with the second time through the loop and beyond, the ListNode
struct to grabs the previous currentVal address and uses it for the next value. In other words, even though I intend to still use this constructor:
ListNode(int x) : val(x), next(nullptr) {}
It seems like this constructor is being used:
ListNode(int x, ListNode *next) : val(x), next(next) {}
...where the next value is the address of the previously created listNode
.
Is there any kind of clear or delete functionality that I can run on listNode
at the end of each loop to prevent this? Is there no way around using new
in this context?
new
when adding nodes to a linked list dynamically. In your "avoid" example, yourlistNode
is a local object that gets destroyed on each loop iteration, leavingt->next
dangling. Using proper memory management techniques when usingnew
will avoid memory leaks.