64,652
社区成员
发帖
与我相关
我的任务
分享
void convert(Node* &node, Node* &nodeList)
{
node->left=nodeList;
cout<<"convert"<<endl;
if(nodeList != NULL)
{
nodeList->right=node;
}
else
{
nodeList=node;
nodeList->right=node->right;
}
cout<<node->value<<endl;
}
10 6 14 4 8 12 16
中序遍历结果:
4 6 8 10 12 14 16
双向链表结果:
4--6--8--10--12--14--16--NULL
反向链表结果:
16 14 12 10 8 6 4
请按任意键继续. . .
#include <iostream>
using namespace std;
typedef struct node
{
struct node *left,*right;
int n;
}Node;
typedef struct binTree
{
Node *root;
int size;
}BinTree;
void initNode(Node *pNode,int n)
{
pNode->left=pNode->right=NULL;
pNode->n=n;
}
void initTree(BinTree *tree)
{
tree->root=NULL;
tree->size=0;
}
void insert(Node *pNode,BinTree *tree)
{
Node *cur=tree->root,*pre=NULL;
bool isLeft;
while(cur!=NULL)
{
pre=cur;
if(pNode->n<cur->n)
{
cur=cur->left;
isLeft=true;
}
else
{
cur=cur->right;
isLeft=false;
}
}
if(pre==NULL)
{
tree->root=pNode;
}
else
{
if(isLeft)
{
pre->left=pNode;
}
else
{
pre->right=pNode;
}
}
++tree->size;
}
void print(Node *pNode)
{
if(pNode!=NULL)
{
print(pNode->left);
cout<<pNode->n<<" ";
print(pNode->right);
}
}
Node* createList(Node *pNode)
{
if(pNode!=NULL)
{
Node *leftHead=createList(pNode->left);
Node *rightHead=createList(pNode->right);
Node *pre=NULL,*cur=leftHead;
while(cur!=NULL)
{
pre=cur;
cur=cur->right; //相当于cur=cur->next
}
pNode->left=pre;
pNode->right=rightHead;
if(pre)
{
pre->right=pNode;
}
if(rightHead)
{
rightHead->left=pNode;
}
if(leftHead == NULL)
{
return pNode;
}
else
{
return leftHead;
}
}
else
{
return NULL;
}
}
int main()
{
BinTree tree;
initTree(&tree);
Node input[7];
int k;
for(int i=0;i<7;++i)
{
cin>>k;
initNode(input+i,k);
insert(input+i,&tree);
}
cout<<"中序遍历结果:"<<endl;
print(tree.root);
cout<<endl;
cout<<"双向链表结果:"<<endl;
Node *list=createList(tree.root),*pre=NULL;
while(list!=NULL)
{
cout<<list->n<<"--";
pre=list;
list=list->right;
}
cout<<"NULL"<<endl;
cout<<"反向链表结果:"<<endl;
while(pre!=NULL)
{
cout<<pre->n<<" ";
pre=pre->left;
}
cout<<endl;
return 0;
}