I am required to write a function in C, that given a pointer to a linked list, will print out the elements in Python syntax: e.g. For the list consisting of 1,2,3,4 and 5, the function will print out [1, 2, 3, 4, 5].
I have tried to write the code as follows:
struct node {
struct node *next;
int data;
};
void print_list(struct node *list) {
printf("[");
if (list == NULL) {
printf("]");
} else {
printf("%d", list->data);
if (list->next != NULL) {
printf(", ");
}
print_list(list->next);
}
}
Output looks like this: [1, [2, [3, [4, [5[]
I understand that every time the function calls itself, "[" will be printed. is there a way to print "[" only when the function is called for the first time?