動態分配儲存的順序表

來源:互聯網
上載者:User

標籤:style   blog   color   io   for   re   

/* * 動態分配儲存的順序表 */#include <stdio.h>#include <stdlib.h>#define INIT_SIZE 100#define EXPAND_SIZE 50typedef 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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.