zoukankan      html  css  js  c++  java
  • 动态分配存储的顺序表

    /*
     * 动态分配存储的顺序表
     */
    
    #include <stdio.h>
    #include <stdlib.h>
    
    #define INIT_SIZE 100
    #define EXPAND_SIZE 50
    
    typedef int ElemType;
    typedef struct {
        ElemType *head;
        int len; // 顺序表当前元素个数
        int size; // 顺序表当前最大容量
    } Sqlist;
    
    int init_sqlist(Sqlist *list)
    {
        if( (list->head = malloc(INIT_SIZE*sizeof(ElemType))) == NULL ) // 分配初始空间
        {
            printf("init error.
    ");
            return -1;
        }
        list->len = 0;
        list->size = INIT_SIZE;
        return 0;
    }
    
    int insert_sqlist(Sqlist *list, int n, ElemType item)
    {
        ElemType *t;
        if( n > list->len+1 || n < 1 ) // 插入位置非法
        {
            printf("insert error, location illegal.
    ");
            return -1;
        }
        if( list->len == list->size ) // 顺序表当前容量已经全部用完, 扩容
        {
            t = realloc( list->head, (list->size + EXPAND_SIZE)*sizeof(ElemType) );
            if( t == NULL)
            {
                printf("realloc error.
    ");
                return -1;
            }
            list->head = t;
            list->size += EXPAND_SIZE;
        }
    
        for( t = list->head + list->len ; t > (list->head + (n-1)) ; t-- ) // 原第n位置元素及其后的元素依次后移
            *t = *(t-1);
        *t = item;
        list->len ++;
        return 0;
    }
    
    int delete_sqlist(Sqlist *list, int n)
    {
        ElemType *t;
        if( n > list->len || n < 1 ) // 删除位置非法
        {
            printf("delete error, location illegal.
    ");
            return -1;
        }
    
        for( t= list->head + (n-1) ; t < list->head + (list->len-1) ; t++ ) // 第n+1位置元素及其后的元素依次前移
            *t = *(t+1);
        list->len --;
        return 0;
    }
    
    int free_sqlist(Sqlist *list)
    {
        free(list->head);
        return 0;
    }
    
    void print_sqlist(Sqlist list)
    {
        int i;
        for(i=0; i<list.len; i++)
            printf("%d ", list.head[i]);
        printf("
    ");
    }
    
    int main(void)
    {
        Sqlist list;
        init_sqlist(&list);
    
        int i;
        for( i=1 ; i<=117; i++)
            insert_sqlist(&list,i,i);
        print_sqlist(list);
    
        delete_sqlist(&list, 5);
        delete_sqlist(&list, 115);
        print_sqlist(list);
    
        free_sqlist(&list);
        return 0;
    }
  • 相关阅读:
    asp.net自带的异步刷新控件使用
    C#反射之创建对象实例
    用httpHandler实现简易ajax框架
    在配置文件中使用相对路径连接数据库文件
    C# 扩展方法
    JavaScript动态创建元素(老帖新发)
    为所有类型扩展一个深拷贝方法
    C#反射之获取程序集信息
    枚举类型的位运算
    SQL2005数据库还原到SQL2000的方法
  • 原文地址:https://www.cnblogs.com/DayByDay/p/3864382.html
Copyright © 2011-2022 走看看