I need to write the following functions in list.cpp, add function prototypes for
ID: 3847232 • Letter: I
Question
I need to write the following functions in list.cpp, add function prototypes for them to list.h and invoke the functions in main.cpp. It should label the output of your test, such as “the list after insertion: “ etc. Thanks!
int sumOfList(node * head)
~compute and return the sum of integers in the linear linked list.
void insert(node *& head, int position, int newInt)
~insert newInt at index “position” where index starts with 0.
// list.h
#include <iostream>
#include <cstring>
#include <cctype>
struct node
{
int data;
node * next;
};
/* These functions are already written and can be called to test out your code */
void build(node * & head); //supplied
void display(node * head); //supplied
void destroy(node * &head); //supplied
void duplicate(node * & new_copy); //provides a duplicate copy of the list
/* *****************YOUR TURN! ******************************** */
//Write your function prototype here:
//
#endif
//main.cpp
#include "list.h"
using namespace std;
int main()
{
node * head = NULL;
build(head);
display(head);
//PLEASE PUT YOUR CODE HERE to call the function assigned
display(head);
destroy(head);
return 0;
}
// list.cpp
#include "list.h"
//put the implementation of your assigned functions here
~
Explanation / Answer
// list.h
#include <iostream>
#include <cstring>
#include <cctype>
struct node
{
int data;
node * next;
};
/* These functions are already written and can be called to test out your code */
void build(node * & head); //supplied
void display(node * head); //supplied
void destroy(node * &head); //supplied
void duplicate(node * & new_copy); //provides a duplicate copy of the list
/* *****************Function prototype******************************** */
int sumOflist(node * head); //returns the sum of data in linear linked list
void insert(node *& head, int position, int newInt); //inserts the data at specified index
#endif
//main.cpp
#include "list.h"
using namespace std;
int main()
{
node * head = NULL;
build(head);
display(head);
//****************Call to functions******************
insert(head,3,7);
sumOflist(head);
cout<<"List after insertion is: "<<endl;
display(head);
destroy(head);
return 0;
}
// list.cpp
#include "list.h"
//*******************Functions Implementation***********************
void insert(node *& head, int position, int newInt)
{
int count=0;
node * temp=head;
while(count!=position-1)
{
temp=temp->next;
count++;
}
node * newNode=(struct node*) malloc(sizeof(struct node));
newNode->data=newInt;
newNode->next=temp->next;
temp->next=newNode;
}
int sumOflist(node * head)
{
int sum=0;
node * temp=head;
while(temp->next!=NULL)
{
sum+=temp->data;
temp=temp->next;
}
return sum;
}