為什么排序樹無法轉換為雙向鏈表,大神求解
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int key;
struct node *pleft;
struct node *pright;
}Node;
int CreateTreeByInsertData(Node **p,int k)//用二級指標
{
if(*p==NULL)
{
printf("\n\t\t請輸入一個整數關鍵字(輸入0時結束輸入):");
scanf("%d",&k);
while(k)
{
int key;
printf("\n\t\t請輸入下一個數關鍵字(輸入0時候結束輸入):");
scanf("%d",&k);
}
*p=(Node *)malloc(sizeof(Node));
(*p)->key=k;
(*p)->pleft=(*p)->pright=NULL;
return 1;
}
else if(k==(*p)->key)
return 0;
else if(k<(*p)->key)
return CreateTreeByInsertData(&(*p)->pleft,k);
else
return CreateTreeByInsertData(&(*p)->pright,k);
}
void InOrderTravel(Node *p)//中序遍歷樹
{
if(p== NULL)
{
InOrderTravel(p->pleft);
printf("%d",p->key);
InOrderTravel(p->pright);
}
}
void ClearTree(Node** tree)//洗掉樹的操作
{
if(*tree==NULL)
return;
ClearTree(&(*tree)->pleft);
ClearTree(&(*tree)->pright);
free(*tree);
*tree=NULL;
}
void TreeToDoublelist(Node *ptr, Node **ListHead, Node **ListTail) //將樹轉換成雙向鏈表
{
if(ptr==NULL)
return;
TreeToDoublelist(ptr->pleft,ListHead,ListTail);
ptr->pleft=*ListTail;
if(*ListTail)
(*ListTail)->pright=ptr;
else
*ListHead=ptr;
*ListTail=ptr;
TreeToDoublelist(ptr->pright,ListHead,ListTail);
}
void printDoubleList(Node *ListHead, Node *ListTail)//列印出雙向鏈表
{
Node* ptr;
printf("Visit the double list from left:\n");
for(ptr=ListHead;ptr;ptr=ptr->pright)
printf("[%d] ",ptr->key);
printf("\n");
printf("Visit the double list from right:\n");
for(ptr=ListTail;ptr;ptr=ptr->pleft)
printf("[%d]",ptr->key);
printf("\n");
}
int main()
{
int i,choice;
Node *proot = NULL;
Node *ListHead = NULL;
Node *ListTail = NULL;
char ch;
ch='y';
while("ch=='y'||ch=='Y'")
{
printf("\n");
printf("\n\t\t 二叉排序樹 ");
printf("\n\t\t****************************");
printf("\n\t\t* 1--建立二叉排序 樹 *");
printf("\n\t\t* 2--中序輸出排序 樹 *");
printf("\n\t\t* 3--樹轉換成雙向鏈表 *");
printf("\n\t\t* 4--列印出雙向鏈 表 *");
printf("\n\t\t* 0--返 回 *");
printf("\n\t\t****************************");
printf("\n\t\t請選擇選單號碼(0--4):");
scanf("%d",&choice);
switch(choice)
{
case 1:
CreateTreeByInsertData(&proot,i);
break;
case 2:
printf("\n");
InOrderTravel(proot);
printf("\n\t\t二叉排序樹輸出完畢.\n");
break;
case 3:
printf("\n");
TreeToDoublelist(proot,&ListHead,&ListTail);
printf("\n\t\t轉換為雙向鏈表.\n");
break;
case 4:
printf("\n");
printDoubleList(ListHead,ListTail);
printf("\n\t\t列印出雙向鏈表.\n");
break;
case 0:
ch='n';
break;
default:
printf("\n\t\t輸入錯誤,請重新輸入.\n");
}
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/53580.html
標籤:C語言
上一篇:請教一下
下一篇:誰能教教我IC卡破解后數字的意思
