Write a C++ function to add a node to the end of a linked list Your function tak
ID: 3906665 • Letter: W
Question
Write a C++ function to add a node to the end of a linked list Your function takes two arguments-the head of the linked list and the value num to be added. Your function should return the head of the linked list. If the list is empty, set the head to point to the new node and return the head pointer. Example: Initial Array: 4->2->3, key 5 Array After Function Call: 4->2->3->5 node* AddNode (node ?ead, int num); The linked list structure: struct node int key node *next; Hi For example Test Result / head2 // AddNode (head, 0) // AddNode (head, 2) // AddNode (head, 2) // AddNode(head, 4) // AddNode(head, 7) 2-> 0?2?2?4?7Explanation / Answer
Hi Student,
Please find the code below :
Node* AddNode(Node *head,int data)
{
// Creates a temp to hold the last node and set last's data and next
Node *last = new Node;
last->key = data;
last->next = NULL;
// If the linked list is empty then set head = last
if (head == NULL) {
head = last;
} else {
// Creates a temp node and sets it to head
Node *temp = new Node;
temp = head;
// Uses temp to find the last node
while (temp->next != NULL) {
temp = temp->next;
}
// Appends the last node with last
temp->next = last;
}
// Returns head of linked list
return head;
}
Happy Coding. :)
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.