2008. 6. 3. 10:50ㆍETC Programmings
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Animal{
char name[20];
double nValue;
struct Animal *pre;
struct Animal *next;
};
struct List {
int length;
struct Animal* first;
struct Animal* last;
};
void initList(struct List*);
void add(struct List*, struct Animal*);
void addInIndex(struct List *, struct Animal *, int);
struct Animal* makeAnimal(char*);
struct Animal* getNodeAt(struct List*, int);
double setWeight(struct Animal*);
void displayList(struct List*, int, int);
void initList(struct List* list){
list->first = NULL;
list->length = 0;
}
void add(struct List *list, struct Animal *animal){
int i;
if(list->length == 0){
list->first = animal;
list->last = animal;
}
else{
for(i = 0 ; i < list->length ; i++){
if(getNodeAt(list, i)->nValue > animal->nValue){
addInIndex(list, animal, i);
break;
}
}
}
list->length++;
}
void addInIndex(struct List *list, struct Animal *animal, int index){
struct Animal *preAni;
struct Animal *curAni;
if(index < 0 || index > list->length){
index = 0;
}
if(index == list->length){
add(list, animal);
}
else if(index == 0){
curAni = list->first;
curAni->pre = animal;
list->first = animal;
animal->next = curAni;
}
else{
preAni = getNodeAt(list, index - 1);
preAni->next = animal;
curAni = getNodeAt(list, index);
curAni->pre = animal;
animal->pre = preAni;
animal->next = curAni;
}
}
struct Animal* makeAnimal(char* name){
struct Animal *newAnimal = (struct Animal*) malloc(sizeof(struct Animal));
strcpy(newAnimal->name,name);
newAnimal->nValue = setWeight(newAnimal);
return newAnimal;
}
struct Animal* getNodeAt(struct List* list, int index){
int i;
struct Animal* current;
if(index <= list->length /2){
current = list->first;
for (i = 0 ; i < index ; i++){
current = current->next;
}
}
else {
current = list->last;
for(i = 1 ; i < list->length - index ; i++){
current = current->pre;
}
}
return current;
}
double setWeight(struct Animal* animal){
char letter;
letter = animal->name[0];
return letter / 128.0;
}
void displayList(struct List *list, int start, int end){
int i;
if(start < 0){
start = 0;
}
if(end >= list->length){
end = list->length;
}
for (i = start ; i < end ; i++){
printf("%d : %s(%.2f)\n",i , getNodeAt(list, i)->name, getNodeAt(list, i)->nValue);
}
}
void main(){
struct List *p_List = (struct List*) malloc(sizeof(struct List));
initList(p_List);
add(p_List, makeAnimal("Tiger"));
add(p_List, makeAnimal("Lion"));
add(p_List, makeAnimal("Monkey"));
add(p_List, makeAnimal("Rabbit"));
add(p_List, makeAnimal("Horse"));
displayList(p_List, 0, p_List->length);
}
아하하 다했당 ㅎㅎ