C语言:【动态顺序表】动态顺序表的初始化、打印、尾插PushBack、尾删PopBack

来源:互联网 发布:旅游购物 知乎 编辑:程序博客网 时间:2024/05/16 12:06
#include<stdio.h>#include<stdlib.h>#include<assert.h>#include<string.h>#include<malloc.h>typedef int DateType;typedef struct SeqList{    DateType *arr;    size_t capacility;    size_t size;}SeqList;//创建空间void CheckCapa(SeqList *Seq){    assert(Seq);    if (Seq->size >= Seq->capacility)    {        Seq->capacility = 2 * Seq->capacility + 3;        Seq->arr = (DateType*)realloc(Seq->arr, Seq->capacility * sizeof(DateType));    }}//初始化动态顺序表void initSeqList(SeqList *Seq){    Seq->arr = NULL/* malloc(sizeof(DateType) * 3)*/;    Seq->capacility = 0;    Seq->size = 0;}//销毁空间void DestroySeq(SeqList *Seq){     Seq->capacility = 0;    Seq->size = 0;    free(Seq->arr);    Seq->arr = NULL;}//尾插void PushBack(SeqList *Seq,DateType x){    assert(Seq);    CheckCapa(Seq);        Seq->arr[Seq->size++] = x;}//尾删void PopBack(SeqList *Seq){    assert(Seq);    if (Seq->size <= 0)    {        printf("当前顺序表为空!无法继续删除\n");        return;    }    --Seq->size;    printf("\n");}//打印动态顺序表void PrintSeq(SeqList *Seq){    assert(Seq);    int index = 0;    if (Seq->size == 0)    {        printf("当前顺序表为空!\n");        return;    }    for (index = 0; index < Seq->size; index++)    {        printf("%d->", Seq->arr[index]);    }    printf("\n");}void Test(){    SeqList Seq;    initSeqList(&Seq);    PushBack(&Seq,1);    PushBack(&Seq, 2);    PushBack(&Seq, 3);    PushBack(&Seq, 4);    PrintSeq(&Seq);    PopBack(&Seq);    PrintSeq(&Seq);    DestroySeq(&Seq);}int main(){    Test();    system("pause");    return 0;}


本文出自 “Han Jing's Blog” 博客,请务必保留此出处http://10740184.blog.51cto.com/10730184/1743504

0 0
原创粉丝点击