This question is a three parter question that refers to the struct in C language
ID: 3597101 • Letter: T
Question
This question is a three parter question that refers to the struct in C language. Thank you for your time.
A linked list of integers is built using the following struct:
struct node {
int data;
struct node *next;
};
1. Write the definition of a function with the following prototype:
void add(struct node* a[], int index, int value);
The first argument is an array of lists (i.e., an array of struct node pointers, each of which points to the head of a list). The second argument is an index into the array, and the third argument is a value to be added. This function inserts the specified value at the head of the indexed list. There is no return value.
Example: add(a, 3, 10) prepends a node containing the integer 10 to the list stored in element 3 of array a.
2. Suppose we have a list of integers. Each node of the list is defined as: struct node { int data; struct node * next; }; Write a function that takes in a list and returns the sum of all of the integers. The declaration of the function is: int sum(struct node * list);
3. Define a function named prepend that creates a new node and adds it to the beginning of a list. The function takes two parameters. The first parameter is a struct node * that points to the head of a list. (This pointer may be NULL.) The second parameter is an integer, which is the value to be stored in the new node. The function returns a pointer to the new list.
Explanation / Answer
Please find my implementaion of linked list.
// A linked list node
struct node
{
int data;
struct node *next;
};
void add(struct node* a[], int index, int value) {
if(index < 0)
return;
// creating new node
struct *newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = value;
// adding new node at head
newNode->next = a[0];
a[0] = newNode;
}
int sum(struct node * list) {
int total = 0;
while(list != NULL) {
total = total + list->data;
list = list->next;
}
return total;
}
/* Given a reference (pointer to pointer) to the head of a list and
an int, inserts a new node on the front of the list. */
struct node* prepend(struct node* head, int new_data)
{
/* 1. allocate node */
struct node* new_node = (struct node*) malloc(sizeof(struct node));
/* 2. put in the data */
new_node->data = new_data;
/* 3. Make next of new node as head */
new_node->next = head;
/* 4. move the head to point to the new node */
head = new_node;
return head;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.