프로그래밍[Univ]/C언어

[C,C++과도기] 링크드리스트 짬봉버전..

Cloud Travel 2009. 4. 9. 00:55


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

typedef struct node node;

struct node {
    char id[20];
    int n;
    struct node * next;
};

class stack{
    public:
        node *start;
        void push(char *id,int s);
        void printall();
        void init();
};

class queue{
    public:
        node *start;
        void Add(char *id,int s);
        node *find(char *id);
        void printall();
        void init();
};

void stack::init(){
    start = 0;
}

void queue::init(){
    start = 0;
}
void stack::push(char *id, int s){
    node * temp;
    temp = (node *)malloc(sizeof(node));
    strcpy(temp->id, id);
    temp->n = s;
    temp->next = start;
    start = temp;
}

void queue::Add(char *id, int s){
    node * temp;
    node * t;
    temp = (node *)malloc(sizeof(node));
    strcpy(temp->id, id);
    temp->n = s;
    t = start;

    if(!start){
        start = temp;
    }
    else{
        while(t->next){
            t = t->next;
        }
        t->next = temp;
    }
}

node * queue::find(char *id){
    node * t;
    t = start;
    while(t){
        if(strcmp(t->id, id)==0){
            return t;
        }
        t = t->next;
    }
}

// pushfun은 리스트의 맨 앞에 새 노드를 추가하는 함수
void stack::printall(){
    node * temp;
    for(temp=start;temp;temp=temp->next){
        printf(" %s, %d -> ", temp->id, temp->n);
    }
    printf("END\n");
}
void queue::printall(){
    node * temp;
    for(temp=start;temp;temp=temp->next){
        printf(" %s, %d -> ", temp->id, temp->n);
    }
    printf("END\n");
}

int main(){
    node * nd;
    char buf[20];

    stack s;
    queue q;
    s.init();
    q.init();

    s.push("20091001",11);
    s.push("20091002",22);
    s.push("20091003",33);
    s.push("20091004",44);
    s.printall();

    q.Add("20091001",11);
    q.Add("20091002",22);
    q.Add("20091003",33);
    q.Add("20091004",44);
    q.printall();

    while (scanf("%s", buf) == 1){
        if (nd = q.find(buf)){
            printf("%s : %d\n", nd->id, nd->n);
        }
        else{
            printf("%s 는 없습니다.\n", buf);
        }
    }
}