프로그래밍[Univ]/데이터구조

[C언어]데이터구조_링크드리스트

Cloud Travel 2009. 3. 22. 20:48


#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct node{
        char name[15];
        int eng;
        int mat;
        struct node *next;
}node_t;

int count = 0;

void insert(node_t *first,char a[],int b,int c,int position){
        int i;
        node_t *new_node = (node_t *)malloc(sizeof(node_t));
        if ( (position < 0) || (position > count) ){
                printf("Error\n");
                return;
        }else if ( position <= count ) {
                for ( i = 0 ; i < position ; i++ )
                        first = first -> next;
        }
        strcpy(new_node->name,a);
        new_node -> eng = b;
        new_node -> mat = c;
        new_node -> next = first->next;
        first -> next = new_node;
        count++;
}

void delete(node_t *first,int position){
        int i;
        node_t *temp;
        if( position >= count ){
                printf("error\n");
                return;
        }
        for ( i = 0 ; i < position ; i++ )
                first = first -> next;
        temp = first -> next;
        first -> next = first -> next -> next;
        free(temp);
        temp = NULL;
        count--;
}

void display(node_t *first){
        int i;
        int total_eng,total_mat;
        total_eng = total_mat = 0;
        first = first -> next;
        for ( i = 0 ; i < count ; i++ ){
                total_eng += first -> eng;
                total_mat += first -> mat;
                printf("Name : %s\tenglish : %d\tmath : %d\n",first->name,first->eng,first->mat);
                first = first -> next;
        }
        printf("total eng average = %f\ttotal math average = %f\n",(float)total_eng/count,(float)total_mat/count);
}

int main(void){
        node_t *start = (node_t *)malloc(sizeof(node_t));
        char name[15];
        int eng,mat;
        int select,pos;
        printf("1.삽입\t2.삭제\t3.출력\n");
        while ( scanf("%d",&select) == 1 ){
                switch(select){
                        case 1 : printf("Name :");
                                 scanf("%s",name);
                                 printf("Math :");
                                 scanf("%d",&mat);
                                 printf("English :");
                                 scanf("%d",&eng);
                                 printf("Position :");
                                 scanf("%d",&pos);
                                 insert(start,name,eng,mat,pos);
                                 break;
                        case 2 : printf("Delete Position :");
                                 scanf("%d",&pos);
                                 delete(start,pos);
                                 break;
                        case 3 : display(start);
                                 break;
                        default : break;
                }
                printf("1.삽입\t2.삭제\t3.출력\n");
        }
}