动态分配存储的顺序表

时间:2014-07-24 09:56:34   收藏:0   阅读:172
/*
 * 动态分配存储的顺序表
 */

#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.\n");
        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.\n");
        return -1;
    }
    if( list->len == list->size ) // 顺序表当前容量已经全部用完, 扩容
    {
        t = realloc( list->head, (list->size + EXPAND_SIZE)*sizeof(ElemType) );
        if( t == NULL)
        {
            printf("realloc error.\n");
            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.\n");
        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("\n");
}

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;
}

动态分配存储的顺序表,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!