主题:树储存结构实现疑问
各位,请问树储存结构里面的双亲表示法,是不是像这样实现:
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#define max 20
typedef struct ptnode
{
char data;
int parent;
}ptnode;
typedef struct ptree
{
ptnode nodes[max];
int n;
}ptree;
create(ptree *ptr)
{
char ch;
int i=0;
printf("input the number nodes:");
scanf("%d",&ptr->n);fflush(stdin);
while(i<ptr->n)
{
if(i==0)
{
printf("Input the node:");
scanf("%c",&ptr->nodes[i].data);
fflush(stdin);
ptr->nodes[i].parent=-1;
i++;
}
else
{ printf("Input the node:");
scanf("%c",&ptr->nodes[i].data);
fflush(stdin);
printf("Input the parent:");
scanf("%d",&ptr->nodes[i].parent);
fflush(stdin);
i++;
}
}
}
main()
{
ptree *p;
int i,j;
p=(struct ptree *) malloc (sizeof(struct ptree));
create(p);
for(i=0;i<p->n;i++)
{
printf("\n%d %c %d\n",i,p->nodes[i].data,p->nodes[i].parent);
}
}
我感觉似乎这样实现效率太低,每个节点的双亲值都是手工输入的,怎样才能改进一下?
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#define max 20
typedef struct ptnode
{
char data;
int parent;
}ptnode;
typedef struct ptree
{
ptnode nodes[max];
int n;
}ptree;
create(ptree *ptr)
{
char ch;
int i=0;
printf("input the number nodes:");
scanf("%d",&ptr->n);fflush(stdin);
while(i<ptr->n)
{
if(i==0)
{
printf("Input the node:");
scanf("%c",&ptr->nodes[i].data);
fflush(stdin);
ptr->nodes[i].parent=-1;
i++;
}
else
{ printf("Input the node:");
scanf("%c",&ptr->nodes[i].data);
fflush(stdin);
printf("Input the parent:");
scanf("%d",&ptr->nodes[i].parent);
fflush(stdin);
i++;
}
}
}
main()
{
ptree *p;
int i,j;
p=(struct ptree *) malloc (sizeof(struct ptree));
create(p);
for(i=0;i<p->n;i++)
{
printf("\n%d %c %d\n",i,p->nodes[i].data,p->nodes[i].parent);
}
}
我感觉似乎这样实现效率太低,每个节点的双亲值都是手工输入的,怎样才能改进一下?