• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

尼古拉斯豆

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

数据结构--堆--链式存储

最小数在根节点,一层比一层大的二叉树.

#include <stdio.h>

typedef int elemType;

struct heap{
    elemType *heap;
    int len;
    int maxsize;
};

/* 1.c初始化堆*/
void initHeap(struct heap *hbt, int ms)
{
    if(ms < 0)
    {
        printf("数组长度参数非法.\n");
        system("pause");    
    }    
    hbt->heap = malloc(sizeof(elemType));
    if(hbt->heap == NULL)
    {
        printf("空间分配失败.\n");
        system("pause");    
    }
    hbt->len = 0;
    hbt->maxsize = size;
    
    return; 
} 
/* 2.清除堆*/
void clearHeap(struct heap *hbt)
{
    if(hbt->heap != NULL)
    {
        free(hbt->heap);
        hbt->heap = NULL;
        hbt->len = 0;
        hbt->maxsize = 0; 
    }      
    return; 
}

/* 3.检查一个堆是否为空,为空返回1,否则返回0*/
int emptyHeap(struct heap *hbt)
{
    if(hbt->heap ==NULL)
    {
        return 1;    
    }else{
        return 0;
    }    
} 
/* 4.向堆中插入一个元素*/
void insertHeap(struct heap *hbt, elemType x)
{
    int i,j;
    if(hbt->len == hbt->maxsize)
    {
        elemType *p;
        p = realloc(hbt->heap, sizeof(elemType));
        if(p == NULL)
        {
            printf("空间申请失败.\n");
            system("pause");    
        }    
        hbt->heap = p;
        hbt->maxsize = 2 * hbt->maxsize;     
    }   
    hbt->heap[hbt->len] = x;
    i = hbt->len;
    hbt->len++;
    
    while(0 != x)
    {
        j = (x-1)/2;
        if(x >= hbt->heap[j])
        {
            break;    
        }    
        hbt->heap[j] = x;
        i = j; 
    } 
    hbt->heap[i] = x;
    return;  
} 
/* 5.从堆中删除元素*/ 
elemType deleteHeap(struct heap *hbt) 
{
    elemType x,temp;
    int i,j;
    
    if(0 == hbt->len)
    {
        printf("堆为空...\n");
        system("pause");    
    } 
    temp = hbt->heap[0];
    hbt->len--;
    if(0 == hbt->len)
    {
        return temp;    
    } 
    i=0;
    j=2*i + 1;
    x = hbt->heap[hbt->len];
    
    while(j <= hbt->len-1)
    {
        if((j < hbt->len -1) && (hbt->heap[j] > hbt->heap[j+1]))    
        {
            j++;    
        } 
        hbt->heap[i] = hbt->heap[j];
        i=j;
        j=2*i+1; 
    } 
    hbt->heap[i] = x;
    return temp; 
} 

posted on 2012-07-10 09:45  尼古拉斯豆  阅读(280)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3