2017年6月4日 星期日

example four for Data Structure Course(Review : find student score maximum)

score.dat
101
Alex
70
102
Bob
46
103
Carlos
78
104
David
34
105
Bo
92
106
Frank
90
說明
Use an ADT List to read all student records from the file “score.dat” and print the detailed student record who has the maximum score. The format of the file “score.dat” is listed as follows: the first column is “Student ID”; the second column is “First Name”; the third column is “Score”. The content of "score.dat" is listed as follows. (from ccu Bo)

輸出範例:
/*the filename: main
 *the filename extension: .c
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "list.h"

L *my_list;

void read_student()
{
    FILE *f;
    int id;
    char name[10];
    int score;
    f = fopen("score.dat", "r");
    while (fscanf(f, "%d %s %d", &id, name, &score)!=EOF)
    {
        insert_first_list(my_list, id, name, score);
    }
    fclose(f);
}


n *get_hscore_student(L *list_head)
{
    n *h_student;
    n *curr;
    if (list_head->count == 0)
    {
        return list_head->head;
    }
    else
    {
        h_student = list_head->head;
        for (curr = h_student->next; curr != NULL; curr = curr->next)
        {
            if (curr->score > h_student->score)
            {
                h_student = curr;
            }
        }
        return h_student;
    }
}

int main()
{
    n *x;
    my_list = (L *) malloc(sizeof(L));
    create_list(my_list);
    read_student();
    x = get_hscore_student(my_list);
    printf("The maximum student:\n%d %s %d",x->id,x->name,x->score);
    return 0;
}

/*the filename: list
 *the filename extension: .h
 */
typedef struct node
{
   int id;
   char name[10];
   int score;
   struct node *next;
}n;

typedef struct list
{
    int count;
    n *head;
}L;

void create_list(L *list_head);
void insert_first_list(L *list_head,int id,char *name,int score);


/*the filename: implement
 *the filename extension: .c
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "list.h"
void create_list(L *list_head)
{
    list_head->count=0;
    list_head->head=NULL;
}
void insert_first_list(L *list_head,int id,char *name,int score)
{
    n *p;
    p = (n *)malloc(sizeof(n));
    p->id=id;
    strcpy(p->name,name);
    p->score=score;
    p->next=list_head->head;
    list_head->head=p;
    list_head->count++;
}

沒有留言:

張貼留言