please help!! trying to write a code using C++ to add an integer value to the en
ID: 3868183 • Letter: P
Question
please help!!
trying to write a code using C++ to add an integer value to the end of a linked list! code isnt working and i think its specifically due to the else statement.
void addIntToEndofList(LinkedList list, int value) t assert (list!=NULL); // if list is NULL, we can do nothing Node *p; // temporary pointer /I TODO: // (1) Allocate a new node. p will point to it. p = new Node; // (2) Set p's data field to the value passed in p->data = value; // (3) Set p's next field to NULL p->next = NULL; if (list->head-NULL) { / (4) Make both head and tail of this list point to p list->headp; list->tail = p; else t // Add p at the end of the list // (5) The current node at the tail? Make it point to p instead of NULL list-tail = p; // (6) Make the tail of the list be p now list->tail->next = p;Explanation / Answer
Please find the program below :
// A linked list node
struct Node
{
int data;
struct Node *next;
};
void addIntToEndOfList(struct Node** head, int value){
// allocate node
struct Node* p = (struct Node*) malloc(sizeof(struct Node));
struct Node *last = *head;
// insert data
p->data = value;
// new node is last node , so make the next as NULL
p->next = NULL;
// if list is empty then new node is the head
if (*head == NULL){
*head = p;
return;
}
else{
// traverse till the last node
while (last->next != NULL)
last = last->next;
}
// Change the next of last node
last->next = p;
return;
}
// print contents of linked list
void printList(struct Node *node){
while (node != NULL)
{
printf(" %d ", node->data);
node = node->next;
}
}
int main(){
struct Node* head = NULL;
// Insert 8
addIntToEndOfList(&head, 8);
// Insert 5 at the end. So linked list becomes 8->5->NULL
addIntToEndOfList(&head, 5);
// Insert 10 at the end. So linked list becomes 8->5->10->NULL
addIntToEndOfList(&head, 10);
printf(" Linked list is: ");
printList(head);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.