Using C, Create a linked list structure Music that contains the data fields Name
ID: 3868432 • Letter: U
Question
Using C, Create a linked list structure Music that contains the data fields Name, Artist, Number_of_Songs, and a pointer to the list. Create the structure with 3 members and fill in data for each member. Create a function that will display() all the data for each member and call it from the main program.Using C, Create a linked list structure Music that contains the data fields Name, Artist, Number_of_Songs, and a pointer to the list. Create the structure with 3 members and fill in data for each member. Create a function that will display() all the data for each member and call it from the main program.
Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
struct node {
char *name;
char *artist;
int num_songs;
struct node *next;
};
struct node *add(struct node *n, char *nm, char *art, int num){
struct node *temp, *ptr;
temp = (struct node *)malloc(sizeof(struct node));
temp->name = (char *)malloc(sizeof(char)*20);
temp->artist = (char *)malloc(sizeof(char)*20);
temp->name = nm;
temp->artist = art;
temp->num_songs = num;
temp->next = NULL;
if (n == NULL){
n = temp;
}
else {
ptr = n;
while (ptr->next != NULL)
ptr = ptr->next;
ptr->next = temp;
}
return n;
}
void display(struct node *n){
struct node *ptr;
ptr = n;
while (ptr != NULL){
printf("--------------------------- ");
printf("Name:%s ", ptr->name);
printf("Artist:%s ", ptr->artist);
printf("Number of songs:%d ", ptr->num_songs);
ptr = ptr->next;
}
printf(" ");
}
int main(){
struct node *start;
start = NULL;
start = add(start,"Name1", "Artist1", 5);
start = add(start,"Name2", "Artist2", 7);
start = add(start,"Name3", "Artist3", 10);
display(start);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.