I need assistance in writing this code for my data structure
I need assistance in writing this code for my data structures class. We just learned about nodes and I don\'t understand them at all. So, if you could also include comments to explain what each line of code is doing. The instructions for the program are written at the top of the attached image.
Thank You!
Write a C++ function to add a node to the end of a linked list. The function takes two arguments the head of the linked list and the value to be added. It should return the head of the linked list. node AddNode(node *head, int key: The linked list structure: struct node int key; node next, You can assume that the head being passed is initialized as follow: node head NULL Answer: 1 struct node 2 3 int key 4 node next 7 node *AddNode(node head, int key) 13 14 CheckSolution
C++ Function:
// Function that adds a node at the end of the list
node *AddNode(node *head, int key)
{
// Creating a new node
node* newNode = new node;
//Assigning data to newly created node
newNode->key = key;
//Making next pointer of new node as NULL
newNode->next = NULL;
//If head node is NULL ( There are no elements in the list )
if(!head)
{
// Making new node as first node
first = newNode;
}
else
{
//Starting from head node
node* lastNode = head;
// Finding last node
while(lastNode->next)
lastNode = lastNode->next;
//Adding new node at the end of the list
lastNode->next = newNode;
}
}
