//将二叉排序树转换成双向链表
#include <iostream>
using namespace std;
//定义节点
struct node{
int num;
node* Lnext;
node* Rnext;
};
class list{
public:
list();
void change(node* p);
void transform();
void mid_order(node* p);
void mid_print();
void inorderBSTree(node* p);
void print();
private:
node* head;
node* phead;
node* pindex;//指向前一个节点
};
void list::mid_print(){
mid_order(head);
}
void list::mid_order(node* p){
if(NULL==p)
return;
mid_order(p->Lnext);
cout<<p->num<<" ";
mid_order(p->Rnext);
}
void list::print(){
node* p;
p=phead;
while(p){
cout<<p->num<<" ";
p=p->Rnext;
}
}
void list::transform(){
inorderBSTree(head);
}
//实现二叉排序树到双向链表的转换,发现规律为Lnext可以等价为back指针,Rnext等价为next指针
void list::inorderBSTree(node* p){
if(p==NULL)
return;
inorderBSTree(p->Lnext);
change(p);
inorderBSTree(p->Rnext);
}
void list::change(node* pcurrent){
if(phead==NULL){
phead=pcurrent;
}
else{
pindex->Rnext=pcurrent;
pcurrent->Lnext=pindex;
}
pindex=pcurrent;
}
//完成二叉排序树的建立
list::list(){
phead=NULL;
pindex=NULL;
node *p,*q;
int i;
cout<<"请输入您想要输入的数字,按任意非数字键结束"<<endl;
cin>>i;
if(cin.fail()&&isspace(cin.peek())){
cout<<"您的输入有误!"<<endl;
exit(-1);
}
head=new node;
head->num=i;
head->Lnext=NULL;
head->Rnext=NULL;
p=head;
while(1){
cout<<"输入您想要的数字"<<endl;
cin>>i;
if(cin.fail())
break;
p=new node;
p->num=i;
p->Lnext=NULL;
p->Rnext=NULL;
q=head;
while(q){
if(p->num<q->num){
if(q->Lnext==NULL){
q->Lnext=p;
break;
}
q=q->Lnext;
}
else{
if(NULL==q->Rnext){
q->Rnext=p;
break;
}
q=q->Rnext;
}
}
}
}
void main()
{
list test;
test.mid_print();
cout<<endl<<endl<<endl<<endl;
test.transform();
test.print();
system("pause");
}
二叉排序树向双向链表的转换
最新推荐文章于 2018-10-25 22:06:59 发布