Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Move into the medium directory and create the file medium.c . In this file you w

ID: 3759076 • Letter: M

Question

Move into the medium directory and create the file medium.c. In this file you will write two functions called sum and count. Both functions will take in a pointer to a linked list node. The function sum will return the sum of the integers found in the linked list. The function count will return the number of integers found in the linked list.

For example, if your linked list contains the integers

The sum function would return the value 34 and the count function would return 6.

For this assignment you will need the files below

Here is a run of the driver if you implement your function correctly

If one of your functions does not work then you will see output similar to

Explanation / Answer

Solution for above problem for count and sum of the linked list is below..

#include<stdio.h>
#include<stdlib.h>

/* Link list node */
struct node
{
    int data;
    struct node* next;
};

/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(struct node** head_ref, int new_data)
{
    /* allocate node */
    struct node* new_node =
            (struct node*) malloc(sizeof(struct node));

    /* put in the data */
    new_node->data = new_data;

    /* link the old list off the new node */
    new_node->next = (*head_ref);

    /* move the head to point to the new node */
    (*head_ref)    = new_node;
}

/* Counts no. of nodes in linked list */
int getCount(struct node* head)
{
    int count = 0; // Initialize count
    struct node* current = head; // Initialize current
    while (current != NULL)
    {
        count++;
        current = current->next;
    }
    return count;
}

int getSum(struct node* head)
{
    int sum1 = 0; // Initialize count
    struct node* current = head; // Initialize current
    while (current != NULL)
    {
        sum1 = sum1 + current->data;;
        current = current->next;
    }
    return sum1;
}

/* Drier program to test count function*/
int main()
{
    /* Start with the empty list */
    struct node* head = NULL;

    /* Use push() to construct below list
     1->2->1->3->1 */
    push(&head, 1);
    push(&head, 3);
    push(&head, 1);
    push(&head, 2);
    push(&head, 1);

    /* Check the count function */
    printf("count of nodes is %d ", getCount(head));
    printf("sum of the nodes is %d", getSum(head));
    return 0;
}

Output is:

count of nodes is 5

sum of the nodes is 8

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote