二叉排序树向双向链表的转换

来源:互联网 发布:java sftp下载 编辑:程序博客网 时间:2024/04/30 22:03
//将二叉排序树转换成双向链表#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");}

原创粉丝点击