A practice problem had me develop some code by following a series of steps, and is now asking that I call several of the functions from within a new function. I'm having some trouble with the syntax of the function declaration and calling the function, and could use some guidance.
The Practice Problem:
- Modify your program to:
- Add a just_checkin function that calls the trav_and_print function to print the data values, prints the number of elements in the linked list (by calling count_elems), and prints the values of first->data and last->data.
I tried a number of approaches, such as including void just_checkin(elementptr);
, just_checkin(first);
in main
, and writing the function as
void just_checkin(elementptr f)
{
trav_and_print(elementptr f);
count_elems(elementptr f);
}
Perhaps unsurprisingly, this did not work. I've also tried shifting the arguments to within the function, calling the functions by means other than feeding (elementptr) through it, and writing out the syntax in a variety of other ways, etc. I'm at a loss.
My prior code, which I'm expected to modify by adding another function:
#include <stdio.h>
#include <stdlib.h>
typedef struct linked_list
{
int data;
struct linked_list *next;
} element;
typedef element * elementptr;
void trav_and_print(elementptr); //prints data values
int count_elems(elementptr); //counts the number of elements in the linked list
int main()
{
elementptr first = NULL;
elementptr last = NULL;
int var = 0;
int NumElems = 0;
/* Create a linked list with one element */
/* NOTE: the first element is always a special case */
first = (elementptr) malloc(sizeof(element));
last = first;
last -> data = 5;
last -> next = NULL;
/* Add another element to the end of the list */
last -> next = (elementptr) malloc(sizeof(element));
last = last -> next;
last -> data = 12;
last -> next = NULL;
/*Add another element to the end of the list;
user generated number*/
last -> next = (elementptr) malloc(sizeof(element));
last = last -> next;
printf("Enter the data value to add to the linked list: ");
scanf("%d",&var);
last -> data = var;
last -> next = NULL;
trav_and_print(first); //prints the linked list
NumElems = count_elems(first); //traverses and counts the elements in the linked list
printf("Number of elements in the linked list: %d",NumElems);
free(first);
free(last);
return 0;
}
void trav_and_print(elementptr f)
{
elementptr current;
current = f;
if(current == NULL)
printf("There is no linked list!\n");
else
while (current != NULL)
{
printf("The data value is %d\n",current->data);
current = current -> next;
}
}
int count_elems(elementptr f)
{
int count = 0;
elementptr current;
current = f;
while(current != NULL)
{
current = current->next;
count++;
}
return count;
}