关闭

微软等公司数据结构面试题1

标签: 数据结构面试微软constructionstructinput
165人阅读 评论(0) 收藏 举报
分类:

 

tree.h
typedef struct BSTreeNode {
int m_value;
struct BSTreeNode *m_left ;
struct BSTreeNode *m_right;
} bstTreeNode;
class ActTree{
public:
ActTree();
void InsertValue() ;
void DeleteValue() ;
void Sort();
void PrintTree();
void PrintNode(bstTreeNode *node);
void ChangeDoubleList();
void Change(bstTreeNode *node);
void addlist(bstTreeNode *node);
void PrintList();
private:
bstTreeNode *currentList;
bstTreeNode *root;
bstTreeNode *first;
};
tree.cpp
#include "tree.h"
#include <cstdlib>
#include <iostream>
ActTree::ActTree()
{
root = NULL;
first = NULL;
// std::cout<<"construction error!"<<std::endl;
}
void ActTree::InsertValue()
{
int temp,flag = 0;
std::cout<<"Input  ";
std::cin>>temp;
bstTreeNode *pnow  = root;
bstTreeNode *pparent  = root;
while( pnow ) {
if( pnow->m_value == temp ){
flag = 1;
pnow = NULL;
std::cout<<"%d has existed!"<<std::endl;
}
else if( pnow->m_value > temp ) {
pparent = pnow ;
pnow = pnow ->m_left ;
}
else {
pparent = pnow ;
pnow = pnow ->m_right ;
}
}
if(!flag) {
if( bstTreeNode *ptemp = (bstTreeNode *) malloc(sizeof (bstTreeNode))) {
ptemp->m_value = temp;
ptemp->m_left = ptemp->m_right = NULL;
if (pparent)
{
if( pparent->m_value > temp ) 
pparent->m_left =ptemp ;
else 
pparent->m_right =ptemp ;
}
else {
root = ptemp;
}
}
else
std::cerr<<"malloc failed!"<<std::endl;
}
}
void ActTree::PrintTree()
{
PrintNode(root);
}
void ActTree::PrintNode(bstTreeNode *node)
{
if( node ){
PrintNode(node->m_left);
std::cout<<node->m_value<<" ";
PrintNode(node->m_right);
}
}
void ActTree::addlist(bstTreeNode *node)
{
if (!first) {
first = node ;
currentList =first;
first->m_left = NULL;
first->m_right = NULL;
}
else {
currentList->m_right = node;
node->m_left =currentList;
node->m_right =NULL;
currentList = node;
}
}
void ActTree::Change(bstTreeNode *node)
{
if (node) {
Change(node->m_left);
bstTreeNode * right = node ->m_right;
addlist(node);
Change(right);
}
else
return ;
}
void ActTree::ChangeDoubleList()
{
this->Change(root);
}
void ActTree::PrintList()
{
bstTreeNode * node = first;
while(node) {
std::cout<<node->m_value<<"=";
node = node->m_right;
}
}
main.cpp
#include "tree.h"
#include <iostream>
int main()
{
ActTree test ;
int select;
//while (std::cin<<select )
test.InsertValue();
test.InsertValue();
test.InsertValue();
test.InsertValue();
test.PrintTree();
std::cout<<std::endl;
test.ChangeDoubleList();
test.PrintList();
getchar();
getchar();
return 0;
}

 

 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:10665次
    • 积分:328
    • 等级:
    • 排名:千里之外
    • 原创:24篇
    • 转载:0篇
    • 译文:0篇
    • 评论:2条
    最新评论