今天一个考研的同学请教了我几道有关数据结构的题目, 下午花了两个小时也算是搞懂了个大概。现将题目记录一下:
1、 由二叉树的前序遍历和中序遍历能确定唯一的一颗二叉树, 下面程序的作用是实现由已知某二叉树的前序遍历和中序遍历,生成一颗用二叉链表表示的二叉树并打印出后序遍历,写出程序所缺语句。
#define MAX 100
typedef struct Node{
char info;
struct Node *llink, * rlink;
}TNode;
char pred[MAX], inod[MAX];
main(int *argc, int * argv){
TNode *root;
if(argc<3)
exit(0);
strcpy(pred, argv[1]);
strcpy(inod, argv[2]);
root = restore(pred,inod,strlen(pred));
postorder(root);
}
TNode *restore(char *ppos, char *ipos, int n){
TNode *ptr; char *rpos; int k;
if(n<=0)
return NULL;
ptr->info =*ppos ;
for(rpos=ipos; rpos<ipos+n; rpos++)
if(*rpos == *ppos)
break;
k=;
ptr->llink = restore(ppos+1,ipos,k);
ptr->rlink = restore(ppos+1+l, rpos+1, n-1-k);
return ptr;
}
postorder(TNode *ptr){
if(ptr==NULL)
exit(0);
postorder(ptr->llink);
postorder(ptr->rlink);
}
2、 Prim算法填空题
const int MaxInt = INT_MAX;
const int n=6;//图的顶点数,有用户自定义
typedef struct{
int fromVex, toVex; //边的起止点
int weight; //边上的权值
} TreeEdgeNode;
typedef TreeEdegeNode MST[n-1]; //最小生成树定义
void PrimMST(AdeMatrix G, MST T, int rt){
//从顶点rt出发构造图G的最小生成树T, rt成为树的根结点
TreeEdgeNode e;
int i, k=0, min, minPos, V;
for(i=0; i<n; i++){ //初始化最小生成树
if(i != rt){
T[k].fromVex = rt;
T[k].toVex = i;
T[k++].weight = G[rt][i];
}// endif
} //endfor
for(k=0; k<n-1; k++){ //依次求MST的候选边
min = MaxInt;
for(i=k; i<n-1; k++){//遍历当前候选边集合
if(T[i].weight < min){ //选具有最小权值的候选边
min = T[i].weight;
mispos = i;
} // endfor
if(min == MaxInt){ //图不联通, 出错处理
cerr<<"Graph is disconnected!"<<endl;
exit(0);
}
e = T[minpos];
T[minpos] = T[k];
T[k] = e;
v = T[k].toVex;
for(i = k+1; i<n-1; i++){// 修改候选边的集合
if(G[v][T[i].toVex] < T[i].weight){
T[i].weight = G[v][T[i].toVex];
T[i].fromVex = v;
}
}
}//endfor
}
}
3、 拓扑排序
void topSort(hnnodes graph[], int n){
int i, j, k, top;
node_pointer ptr;
top = -1;
for(i=0; i<n; i++){
if(! graph[i].count){
graph[i].count = top;
top = i;
}
}
for(i=0; i<n; i++){
if(top == -1){
fprintf(stderr, "/n graph has a circle!/n");
}
else{
j = top;
top = graph[j].count;
printf("v %d ,", j);
for(ptr = graph.link; ptr; ptr=ptr->link){
k = ptr->vertex;
graph[k].count--;
if(graph[k].count ==0 ){
graph[k].count = top;
top = k;
}
}
}
}
}