树和二叉树
[1]二叉树
-
满二叉树
- 结点个数2^k-1(k为深度)
-
完全二叉树
- 2^k-1 -1 <结点个数<2^k -1
-
先序、中序、后序遍历代码实现
/*先序遍历*/ void prev_printf(Node *root){ if(root){ printf("%d ",root->data); prev_printf(root->left); prev_printf(root->right); } } /*中序遍历*/ void mid_printf(Node *root){ if(root){ mid_printf(root->left); printf("%d ",root->data); mid_printf(root->right); } } /*后序遍历*/ void end_printf(Node *root){ if(root){ end_printf(root->left); end_printf(root->right); printf("%d ",root->data); } }
哈希表
[1]线性探测法解决冲突
- 此方法定义哈希表是一个数组,根据关键字除留取余所得到的的下标,将关键字放到表中对应下标的位置;
- 若该位置已有数据,则发生冲突,通过线性探测法,遍历其余下标(实现方法代码可见),挨个检测当前位置中是否有元素,没有则直接插入。
/*除留余数法*/
int hash_fun(int key){
return key%LEN;
}
/*数据插入*/
int hash_insert(int hash_table[], int key){
int index;
index = hash_fun(key);
if(hash_table[index] == 0){
hash_table[index] = key;
return 0;
}
/*解决冲突---->线性探测法解决冲突*/
for(int i=1; i<LEN; i++){
/*线性遍历其余下标*/
int index1 = hash_fun(index+i);
if(hash_table[index1] == 0){
hash_table[index1] = key;
return 0;
}
}
return -1;
}
/*查找*/
void hash_search(int hash_table[]){
int key;
printf("输入查找的关键字:");
scanf("%d",&key);
while(getchar()!='\n');
int index = hash_fun(key);
if(hash_table[index] == key){
printf("hash_table[%d] = %d\n",index,hash_table[index]);
}
else{
int index1;
for(int i = 1;i < LEN;i++){
index1 = hash_fun(index+i);
if(hash_table[index1] == key){
break;
}
}
printf("hash_table[%d] = %d\n",index1,hash_table[index1]);
}
}
/*打印哈希表中数据*/
void hash_show(int hash_table[]){
for(int i=0; i<LEN; i++){
printf("hash_table[%d] = %d\n", i, hash_table[i]);
}
}
[2]链地址法解决冲突
- 此方法的定义的哈希表是一个结构体指针数组,保存每一条链表头指针的地址;
- 还是使用除留余数法,通过得到下标确定放入哪条链表;
- 解决冲突的方法是将关键字直接插到哈希表对应下标所保存的链表中。
/*数据插入*/
void hash_insert(struct node* hash_table[], int key){
int index;
index = hash_fun(key);
struct node *pnew = NULL;
pnew = (struct node *)malloc(sizeof(struct node));
assert(pnew!=NULL);
pnew->data = key;
pnew->next = NULL;
if(hash_table[index] == NULL){
hash_table[index] = pnew;
}
else{
struct node *p = hash_table[index];
while(p->next != NULL){
p = p->next;
}
p->next = pnew;
}
return ;
}
/*查找数据*/
void hash_search(struct node *hash_table[]){
int key;
printf("输入查找的关键字:");
scanf("%d",&key);
while(getchar()!='\n');
int index = hash_fun(key);
struct node *p = hash_table[index];
while(p != NULL){
if(p->data == key){
printf("在第%d条链表:%d\n",index,p->data);
break;
}
p = p->next;
}
}
/*打印哈希表中数据*/
void hash_show(struct node* hash_table[]){
for(int i=0; i<LEN; i++){
if(hash_table[i] == NULL){
printf("第%d条链表暂无数据!\n", i);
}
else{
struct node *p = hash_table[i];
printf("第%d条链表的数据如下:", i);
while(p != NULL){
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
}
}