逻辑:
一.实验步骤
1.定义十字链表
2.建立十字链表
3.打印输出
(1)以矩阵格式输出
(2)以三元组表格式输出
二.输出结果
1.
2.
三.实验代码
#include <stdio.h>
#include <stdlib.h>
/*二叉树的存储结构(二叉链表)*/
typedef struct node{
int num;
char data;
struct node *lchild,*rchild;
}bitree;
bitree *Q[20];
bitree *CREATREE()
{
char ch;
int front,rear,n=1;
bitree *root,*s;
root=NULL;
front=1,rear=0;
ch=getchar();
while(ch!='#')
{
s=NULL;
if(ch!='@')
{
s=(struct node*)malloc(sizeof(bitree));
s->data=ch;
s->num=n;
n++;
s->lchild=NULL;
s->rchild=NULL;
}
rear++;
Q[rear]=s;
if(rear==1)root=s;
else
{
if(s&&Q[front])
if(rear%2==0) Q[front]->lchild=s;
else
Q[front]->rchild=s;
if(rear%2==1) front++;
}
ch=getchar();
}
return root;
}
//中序遍历
void INORDER(bitree *t)
{
if(t)
{
INORDER(t->lchild);
printf("%C[%d]\t",t->data,t->num);
INORDER(t->rchild);
}
}
//中序遍历找A
int w=1;
void SEARCHINORDER(bitree *t)
{bitree *y;
if(t&&w)
{
SEARCHINORDER(t->lchild);
if(t->data=='A'){
w=0;
printf("%d\n",t->num);
}
SEARCHINORDER(t->rchild);
}
}
//前序遍历
void PREORDER(bitree *t)
{
if(t)
{
printf("%C[%d]\t",t->data,t->num);
PREORDER(t->lchild);
PREORDER(t->rchild);
}
}
//前序遍历找A
int v=1;
void SEARCHPREORDER(bitree *t)
{bitree *y;
if(t&&v)
{
if(t->data=='A'){
v=0;
printf("%d\n",t->num);
}
SEARCHPREORDER(t->lchild);
SEARCHPREORDER(t->rchild);
}
}
//后序遍历
void POSTORDER(bitree *t)
{
if(t)
{
POSTORDER(t->lchild);
POSTORDER(t->rchild);
printf("%C[%d]\t",t->data,t->num);
}
}
//后序遍历找A
int u=1;
void SEARCHPOSTORDER(bitree *t)
{bitree *y;
if(t&&u)
{
SEARCHPOSTORDER(t->lchild);
SEARCHPOSTORDER(t->rchild);
if(t->data=='A'){
u=0;
printf("%d\n",t->num);
}
}
}
int main()
{
bitree *T;
T=CREATREE();
printf("前序遍历:\n");
PREORDER(T);
printf("\n利用前序遍历查找第一个A的位置为:");
SEARCHPREORDER(T);
printf("\n中序遍历:\n");
INORDER(T);
printf("\n利用中序遍历查找第一个A的位置为:");
SEARCHINORDER(T);
printf("\n后序遍历:\n");
POSTORDER(T);
printf("\n利用后序遍历查找第一个A的位置为:");
SEARCHPOSTORDER(T);
}