문자열 정렬
#include <malloc.h>
#include <stdio.h>
#include <string.h>
struct tree {
char info[20];
int cnt;
struct tree * left,*right;
}*root;
FILE *in,*out;
void insert(char *);
void inorder(struct tree *);
void main(){
char value[20];
in =fopen("word.dat","r");
out = fopen("freq.out","w");
while(fscanf(in,"%s",value),(strcmp(value,"/*")!=0))
insert(value);
fprintf(out,"\tWords\t\t\tFrequencies\n");
inorder(root);
fclose(in);
fclose(out);
}
void insert(char val[20])
{
static struct tree *newnode, *p, *back;
newnode=(struct tree *)malloc(sizeof *root);
newnode->left=0;
newnode->right=0;
strcpy(newnode->info, val);
newnode->cnt=1;
p=root;
back=0;
while (p!=0)
{
back = p;
if (strcmp(p->info, val) > 0) p=p->left;
else if (strcmp(p->info, val) < 0) p=p->right;
else {
p->cnt++;
break;
}
};
if (back == 0) root=newnode;
else if(strcmp(back->info, val) > 0) back->left=newnode;
else if(strcmp(back->info, val) < 0) back->right=newnode;
}
void inorder(struct tree *p)
{
if(p !=0)
{
inorder(p->left);
fprintf(out, "\t%-20s\t: %5d\n",p->info, p->cnt);
inorder(p->right);
}
}
출력 예제
input file : word.dat
multiprogramming CPU ciphertext plaintext interleaving multiprogramming
information interrupt memory synchronous instruction information ALU
complement compiler instruction interrupt bus instruction information
multiplexer mapping cyclestealing information CPU compiler information
interrupt mapping information CPU /*
output file : freq.out
Words Frequencies
ALU : 1
CPU : 3
bus : 1
ciphertext : 1
compiler : 2
complement : 1
cyclestealing : 1
information : 6
instruction : 3
interleaving : 1
interrupt : 3
mapping : 2
memory : 1
multiplexer : 1
multiprogramming : 2
plaintext : 1
synchronous : 1
숫자 정렬
#include <malloc.h>
#include <stdio.h>
#include <string.h>
#include <windows.h>
struct tree {
int info;
struct tree * left,*right;
}*root;
void insert(int);
void inorder(struct tree *);
void main()
{
int value;
printf("숫자를 입력하세요(같은 숫자 무시, 종료 : -9999) : ");
while(scanf("%d", &value), value != -9999)
insert(value);
inorder(root);
}
void insert(int val)
{
static struct tree *newnode, *p, *back;
newnode=(struct tree *)malloc(sizeof *root);
newnode->left=0;
newnode->right=0;
newnode->info = val;
p=root;
back=0;
while (p!=0)
{
back = p;
if (p->info > val)
p=p->left;
else if (p->info < val)
p=p->right;
else
break;
};
if (back == 0) root=newnode;
else if(back->info > val)
back->left=newnode;
else if(back->info < val)
back->right=newnode;
}
void inorder(struct tree *p)
{
if(p !=0)
{
inorder(p->left);
printf("%10d\n",p->info);
inorder(p->right);
}
}
'프로그래머의 길 > C & C++' 카테고리의 다른 글
오늘의 날짜를 리턴해 주는 함수 <time.h> (0) | 2007.04.12 |
---|---|
디렉토리 관련 함수 (0) | 2007.04.09 |
const의 정확한 이해 (0) | 2007.03.26 |
조건부 컴파일 전처리 명령어 (0) | 2007.03.26 |
C로 만든 숫자 야구 프로그램 (0) | 2007.03.24 |