Currently I am trying to create a linked list, which i think is
a data structure composed of nodes where each node stores an item and a pointer to the next node in the data structure.
Here is the class I am using to create nodes:
class node{
public:
int item;
node* ptr_next;
node(int new_item = 0, node* new_ptr_next = nullptr):
item(new_item), ptr_next(new_ptr_next){}
};
Here is the function I have used to add nodes to the tree:
//Adds a node to the end of the linked list.
//by making the last node point to the new node
node append_node(const int& item, node* ptr_entry_node){
node* ptr_last_node;
node* ptr_current_node;
//Finds Last Node In List
ptr_current_node = ptr_entry_node;
while (ptr_current_node->ptr_next != nullptr){
ptr_current_node = ptr_current_node->ptr_next;
}
ptr_last_node = ptr_current_node;
//Instanciates a new node and makes the last node point to the new node
node new_node(item);
ptr_last_node->ptr_next = &new_node;
return new_node;
}
Here is the main program.
int main(){
//Creates a node for the beggining of the linked list.
node entry_node;
append_node(12,&entry_node);
std::cout<<entry_node.item<<"n";
std::cout<<entry_node.ptr_next->item<<"n";
}
When I run main()
, I receive the following output:
0
12
This is the output i expect.
however if i change append_node
to:
void append_node(const int& item, node* ptr_entry_node){
//Exact same code but no "return new_node;"
}
When I run main()
, I receive the following output:
0
-1108142424
The second number outputted changes when i run the program again.
This is not what i expect.
I would greatly appreciate your help, if someone could explain why i need to return new_node;
in `append_node’, for the new node to be added to the linked list successfully.