中序遍历二叉树将遍历结果存入双向循环链表C语言实现
新浪面试题
#include
#include
#include
#define OK 1
#define Error 0
typedef int Status;
typedef char ElemType;
//循环链表的定义
typedef struct DuLNode
{
ElemType data;
struct DuLNode *prior;
struct DuLNode *next;
}DuLNode,*DuLinkList;
//二叉树的定义
typedef struct BiNode
{
ElemType data;
struct BiNode *lchild,*rchild;
}BiNode,*BiTree;
//先序建立二叉树
void CreateBiTree(BiTree &T)//引用
{
ElemType ch;
T=(BiTree)malloc(sizeof(BiNode));
scanf("%c",&ch);
if (ch=='.')//判断输入
T=NULL;
else
{
if (!T)//判断分配空间
{
printf("分配空间失败!");
return;
}
T->data=ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
//建立空双向循环链表
Status CreateDuLinkList(DuLinkList &L)
{
L=(DuLinkList)malloc(sizeof(DuLNode));
if (!L)
return Error;
else
{
L->data=NULL;
L->prior=L;
L->next=L;
return OK;
}
}
//元素插入双向循环链表
Status InsertDuLinklist(DuLinkList L,BiTree T)
{
if (!T)//二叉树非空
return Error;
else
{
if (!L)//循环链表非空
return Error;
else
{
DuLinkList s,p;
s=(DuLinkList)malloc(sizeof(DuLNode));
if(!s)
return Error;
else
{
p=L;//头结点
s->data=T->data;
p->prior->next=s;//1
s->prior=p->prior;//2
s->next=p;//3
L->prior=s;//4
return OK;
}
}
}
}
//中序遍历二叉树改为双向循环链表
Status InOrderTraverse(BiTree T,DuLinkList L)
{
if (T)//非空
{
InOrderTraverse(T->lchild,L);//
InsertDuLinklist(L,T);
InOrderTraverse(T->rchild,L);
return OK;
}
return Error;
}
void main()
{
ElemType t;
BiTree T;
DuLinkList L,q;
CreateDuLinkList(L);//建空双向循环链表
printf("请输入二叉树(形式为abc..de.g..f...)。并以句号结束:\n");
CreateBiTree(T);//引用
printf("中序遍历二叉树并建立循环链表:\n");
InOrderTraverse(T,L);
printf("输出双向循环链表:\n");
q=L->next;
t=q->data;
while(q->data)//非空
{
t=q->data;
printf("%c ",q->data);
q=q->next;
}
getch();
}