c·c++/c 프로그래밍

연결리스트, 단어세기

바로이순간 2012. 6. 14. 12:25

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

typedef struct _symbol symbol; 

typedef struct _symbol *psym; 

struct _symbol {

    char name[30];

    int count;

    psym next;

};

psym makeSymbol(char *name) {

    psym s;

    s=(psym)malloc(sizeof(symbol));

    strcpy(s->name, name);

    s->count=1;

    s->next=NULL;

    return s;

}

void insert(psym list, char *name) {

    psym s=list;

    while(s) {

        if(strcmp(s->name,name)==0) {

            s->count++; 

            return;

        }

        if(s->next) s=s->next;

        else break;

    }

    s->next=makeSymbol(name);

}

void printList(psym list) {

    psym s=list->next;

    while(s) {

        printf("%s %d\n", s->name, s->count);

        s=s->next;

    }

}    

int main(void) {

    psym head=makeSymbol(""); // 더미 symbol을 가지고 있슴

    char *token;

    char s[100];

    char seps[] = " ,\t\n";

    int i, j;

    printf("텍스트를 입력하시오. : ");

    gets(s);

    token = strtok(s, seps);

    while(token!=NULL) {

        insert(head, token);

        token = strtok(NULL, seps);

    }

    printList(head);


    return 0;

}