[面试备忘]样例代码共用头文件general.h

样例代码共用头文件general.h

包含常用头文件,数据结构定义及全局函数。

View Code
#ifndef _GENERAL_H_
#define _GENERAL_H_
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) == MIN((a), (b)) ? (b) : (a))
typedef
struct __node
{
int value;
__node
* next;
} NODE,
*PNODE;
typedef
const NODE* CPNODE;

typedef
struct __tnode
{
char value;
__tnode
* left;
__tnode
* right;
} TNODE,
*PTNODE;
typedef
const TNODE* CPTNODE;

PNODE createList(
int length)
{
if (!length) {
return NULL;
}
PNODE head
= new NODE();
head
->value = 0;
head
->next = NULL;
PNODE tail
= head;
for (int index = 1; index != length; ++index) {
PNODE temp
= new NODE();
temp
->value = index;
temp
->next = NULL;
tail
->next = temp;
tail
= temp;
}
return head;
}

void destroyList(PNODE head)
{
while (head != NULL) {
PNODE nextNode
= head->next;
delete head;
head
= nextNode;
}
}

void printList(CPNODE head)
{
while (head != NULL) {
std::cout
<< head->value << ' ' << std::flush;
head
= head->next;
}
std::cout
<< std::endl;
}

void preOrderP(CPTNODE root)
{
if (root == NULL) {
return;
}
std::cout
<< root->value << ' ' << std::flush;
preOrderP(root
->left);
preOrderP(root
->right);
}

void preOrderPrint(CPTNODE root)
{
preOrderP(root);
std::cout
<< std::endl;
}

void inOrderP(CPTNODE root)
{
if (root == NULL) {
return;
}
inOrderP(root
->left);
std::cout
<< root->value << ' ' << std::flush;
inOrderP(root
->right);
}

void inOrderPrint(CPTNODE root)
{
inOrderP(root);
std::cout
<< std::endl;
}

void postOrderP(CPTNODE root)
{
if (root == NULL) {
return;
}
postOrderP(root
->left);
postOrderP(root
->right);
std::cout
<< root->value << ' ' << std::flush;
}

void postOrderPrint(CPTNODE root)
{
postOrderP(root);
std::cout
<< std::endl;
}

void buildBinaryTree(const char* pPreOrder, const char* pInOrder, int length, PTNODE& root)
{
if (length == 0) {
root
= NULL;
return;
}
root
= new TNODE();
root
->value = pPreOrder[0];
int inOrderRootIndex = 0;
for ( ; inOrderRootIndex != length; ++inOrderRootIndex) {
if (pInOrder[inOrderRootIndex] == pPreOrder[0]) {
break;
}
}
buildBinaryTree(reinterpret_cast
<const char*>(pPreOrder + 1), pInOrder,
inOrderRootIndex, root
->left);
buildBinaryTree(reinterpret_cast
<const char*>(pPreOrder + 1 + inOrderRootIndex),
reinterpret_cast
<const char*>(pInOrder + 1 + inOrderRootIndex),
length
- 1 - inOrderRootIndex, root->right);
}
#endif

  

posted @ 2011-09-05 14:55  lifengzhong  阅读(237)  评论(0编辑  收藏  举报