File supplied.o contains code that can build, display, duplicate, and destroy a
ID: 3736340 • Letter: F
Question
File supplied.o contains code that can build, display, duplicate, and destroy a linear linked list. For this test, you will need to write the following functions in list.cpp, add function prototypes for them to list.h and invoke the functions in main.cpp. You should label the output of your test, such as "the list after insertion: "etc. 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 newlnt at index "position" where index starts with 0Explanation / Answer
Please find my implementation of two mentioned functions:
int sumOfList(node *head) {
int sum = 0;
while(head != NULL) {
sum = sum + head->data;
head = head->next;
}
return sum;
}
void insert(node *&head, int position, int newInt) {
node *newNode = new node;
newNode->next = NULL;
newNode->data = newInt;
if(position == 1) {
newNode->next = head;
head = newNode;
return;
}
// traverse the first linked list until k-th
// point is reached
int count = 1;
struct node* curr = head;
while (count < position)
{
curr = curr->next;
count++;
}
// backup next node of the k-th point
node* temp = curr->next;
// join second linked list at the kth point
curr->next = newNode;
newNode->next = temp;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.