Struct and Linked List Revision - SOLUTION
-
Upload
sabrina-noor -
Category
Documents
-
view
212 -
download
0
description
Transcript of Struct and Linked List Revision - SOLUTION
Struct and Linked List Revision
Question 1.1 (3 marks)
Create a struct called mystruct. There are two items in this struct, one is a string of 50 characters called name and the other is a self-reference pointer.
struct mystruct{char name[50];struct mystruct *next;
};
Question 1.2 (2 marks)
Define a new type called Node for the struct that you created in Question 1.1. Define a global variable called footer that will always point to the last element in your linked list.
typedef struct mystruct node;
node *footer = NULL;
Question 1.3 (10 marks)
Create a makenode function that dynamically allocates memory space for a new node in your linked list. Fill the name property in your new node by user-defined functions. Ensure that you update your footer to accommodate the new node in your linked list.
Your Answer:
void makenode(){node *temp;temp = (node *) malloc(sizeof(node));fflush(stdin);printf("What is the name? ");scanf("%s",temp->name);if (footer==NULL) {
footer=temp;temp->next = NULL;
}else {
temp->next=footer;footer=temp;
}}
Question 1.4 (8 marks)
Create a function called max that will return the length of the longest string in your linked list.
Your Answer:
int max(node *start){int length=-1, check=-1;node *temp = start;while(temp !=NULL){
check = strlen(temp->name);if (check>length) length = check;temp = temp->next;
}return length;
}
Question 1.3 (7 marks)
In your main program, create a choice menu that allows the user to do the following:
1. If the user selects “1”, call the makenode function. After that, loop back to the choice menu.2. If the user selects “2”, call the max function. Print out the value returned by max. After that,
loop back to the choice menu.3. If the user selects “3”, exit the program.4. If the user selects any other number, print “Invalid Selection” on to the console. After that,
loop back to the choice menu
int main(){int length;int choice=0;
do{fflush(stdin);printf("\n\n\nChoice Menu\n*****************************\n");printf("1. Make a new entry\n2. Get the length of the longest string in
the list\n3. Exit the program.\n");printf("Your Choice: ");scanf("%d",&choice);
switch(choice){case 1:
makenode();break;
case 2: length = max(footer);if (length == -1) printf("There is no data!\n");else printf("The longest string has %d characters.\n",
length);break;
case 3:fflush(stdin);printf("End of program.\n");getchar();break;
default:printf("Invalid Selection!\n");break;
}}while(choice !=3);
return 0;}