前田稔(Maeda Minoru)の超初心者のプログラム入門
![]()
![]()
struct TREE
{ struct TREE *car;
struct TREE *cdr;
int v;
};
|
| car | 自分より小さいデータを格納する構造体へのポインタ |
| cdr | 自分より大きいデータを格納する構造体へのポインタ |
| v | ソートのキー項目 |
struct TREE t2= { NULL,NULL,1 };
struct TREE t4= { NULL,NULL,3 };
struct TREE t5= { NULL,NULL,5 };
struct TREE t3= { &t4, &t5, 4 };
struct TREE t1= { &t2, &t3, 2 };
struct TREE *PT= &t1;
|
| *PT | Binary Tree 構造の親ポインタで t1 を指します |
| t1 | v=2 で、t2(小さい)とt3(大きい)をポイントします |
| t2 | v=1 で、下位の構造はありません |
| t3 | v=4 で、t4(小さい)とt5(大きい)をポイントします |
| t4 | v=3 で、下位の構造はありません |
| t5 | v=5 で、下位の構造はありません |

/*★ Binary Tree を昇順に印字する 前田 稔 ★*/
#include <stdio.h>
struct TREE
{ struct TREE *car;
struct TREE *cdr;
int v;
};
struct TREE t2= { NULL,NULL,1 };
struct TREE t4= { NULL,NULL,3 };
struct TREE t5= { NULL,NULL,5 };
struct TREE t3= { &t4, &t5, 4 };
struct TREE t1= { &t2, &t3, 2 };
struct TREE *PT= &t1;
// Binary Tree を昇順に表示
void list(struct TREE *pt)
{
if (pt==NULL) return;
if (pt->car!=NULL) list(pt->car);
printf("%5d",pt->v);
if (pt->cdr!=NULL) list(pt->cdr);
}
//☆ MAIN
int main()
{
list(PT);
printf("\nEnd Data\n");
return 0;
}
|
![]()
#define MAX 100
struct TREE *PT;
struct TREE TR[MAX];
int t[MAX] = { 10, 7, 2, 10, 5, 3, 6, 9, 1, 4, 8 };
:
void sort(int t[], int n)
{ int i;
PT= NULL;
for(i=0; i<n; i++)
{ TR[i].car=TR[i].cdr= NULL;
TR[i].v= t[i];
app(&PT,&TR[i]);
}
}
|
void app(struct TREE **pt, struct TREE *w)
{
if (*pt==NULL) { *pt= w; return; }
if ((*pt)->v > w->v) app(&(*pt)->car,w);
else app(&(*pt)->cdr,w);
}
|
![]()
![]()