#include <stdio.h>
#include <stdlib.h>
/*Define the data type of an element*/
typedef struct student
{ int id;
char name[20];
int classes;
float score[4];
}elemtype;
/*Define the data type of a single linked list*/
struct node
{ elemtype data;
struct node *next;
};
/*Define the function to initialize a single linked list*/
void initiatelist ( struct node ** h )
{ *h = (struct node *) malloc (sizeof (struct node) );
(*h)->next = NULL;
}
/*Define the function to insert an element into the list*/
void insertsl ( struct node *h, int i, elemtype x )
{struct node *p, *t;
int j;
p = h; j = 0;
while ( p->next!= NULL && j<i-1 )
{ p = p->next; j++; }
if ( j != i-1 ) { printf ( " i is invalid " ); return;};
t = (struct node *) malloc ( sizeof (struct node) );
t->data = x;
t->next = p->next;
p->next = t;
}
/*Define the function to delete an element from the list*/
void deletesl ( struct node *h, int i )
{struct node *p, *s;
int j;
p = h; j = 0;
while ( p->next != NULL && j<i-1 )
{ p = p->next; j++; }
if ( p->next == NULL || j != i-1 )
{ printf ( " i is invalid " ); return; }
s = p->next;
p->next = s->next;
free(s);
printf(" Successfully Delete!");
}
/*Define the function to access the element */
elemtype access ( struct node *h, int i )
{struct node *p;
int j,k;
p = h; j = 0;
while ( p->next != NULL && j<i )
{ p = p->next; j++; }
if ( j == i ){
printf("ID:%d NAME:%s CLASS:%d SCORES:",p->data.id,p->data.name,p->data.classes);
for(k=0;k<4;k++)
printf("%3.1f ",p->data.score[k]);
}
printf(" Cannot Access!");
}
int main()
{
struct node * head;
elemtype new;
int i,j,k;
initiatelist(&head);
while(1)
{
/*Display a menu*/
printf("\n\n1.Insert\n2.Delete\n3.Access\n4.exit\n");
scanf("%d", &j);
switch(j)
{
case 1:
printf("the inserted student is No:");
scanf("%d",&i);
printf("the No.%d student's id:\n",i);
scanf("%d",&new.id);
printf("the No.%d student's name:\n",i);
scanf("%s",new.name);
printf("the No.%d student's class:\n",i);
scanf("%d",&new.classes);
printf("the No.%d student's scores:\n",i);
for(k=0;k<4;k++){
scanf("%f",&new.score[k]);
}
insertsl ( head, i, new);break;
case 2:
printf("\n\nplease enter the deleted ID:"); scanf("%d", &i);
deletesl ( head, i );break;
case 3:
printf("\n\nplease enter the accessed ID:"); scanf("%d",&i);
access ( head, i );
break;
case 4:
return 0;
}
}
}