Jumat, 11 Juni 2010

Codingan Shift 1 Modul 4

#include
#include
#include

typedef struct tree
{
char data[100];
int arah;
struct tree *left;
struct tree *right;
};

tree *make(char x[], int);
tree *add(tree *, char x[], int);
void cari(tree *, char x[]);

int main()
{
tree *root = NULL;
char a[100], b[100];
int n, c=0;
printf("Masukkan jumlah pemilik rumah: ");
scanf("%d", &n);

printf("Masukkan nama-nama pemilik rumah: ");
printf("\n");
while(c < n)
{
scanf("%s",a);
c++;
root = add(root, a,0);
}
printf("Masukkan nama pemilik rumah yang ingin dicari: ");
scanf("%s", b);
cari(root,b);

printf("\n");
system("pause");

return 0;
}

tree *make(char *x, int arah)
{
tree *node;
node = (tree *)malloc(sizeof(tree));
strcpy(node->data, x);
node->arah = arah;
node->left = NULL;
node->right = NULL;

return node;
}

tree *add(tree *root, char *x, int arah)
{
if(root == NULL)
{
root = make(x,arah);
return root;
}
else
{
if(strcmp(root->data, x) == -1)
{
root->right = add(root->right, x, 2);
}
else if(strcmp(root->data, x) == 1)
{
root->left = add(root->left, x, 1);
}

return root;
}
}

void cari(tree *root, char *x)
{
tree *s = root;
while(s!= NULL)
{
if(s->arah == 1)
printf("jalan ke kiri,");
else if(s->arah == 2)
printf("jalan ke kanan,");

if(strcmp(s->data,x) == 0)
{
printf("anda sampai di rumah %s\n",s->data);
break;
}
else if(s->arah!=0)
printf("rumah %s\n",s->data);

if(strcmp(s->data,x) == -1)
s = s->right;
else if(strcmp(s->data,x) == 1)
s = s->left;
}
if(s==NULL)
puts("rumah tidak ditemukan");
}

Tidak ada komentar:

Posting Komentar