您的位置:首页 > 编程语言 > C语言/C++

C语言:【动态顺序表】动态顺序表的在指定位置插入元素Insert,以及指定元素Find

2016-02-19 22:10 507 查看
#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 Insert(SeqList *Seq,size_t pos, DateType x)
{
assert(Seq);
assert(pos < Seq->size);
CheckCapa(Seq);
//思路:插入时将pos+1之后元素往后移腾出一个位置,pos位置放入x。
//鉴于标号从0开始,先移动再加加size。
int index = Seq->size;
for (; index >= pos + 1;index--)
{
Seq->arr[index] = Seq->arr[index - 1];
}
Seq->arr[pos] = x;
Seq->size++;
}

//查找
int Find(SeqList *Seq, DateType x)
{
assert(Seq);
int index = 0;
for (; index < Seq->size; index++)
{
if (Seq->arr[index] == x)
{
return index;
}
}
return -1;
}

//打印动态顺序表
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);

Insert(&Seq, 2, 10);
PrintSeq(&Seq);

int ret = Find(&Seq, 20);
if (ret == -1)
{
printf("not exist!\n");
}
else
{
printf("%d\n");
}
DestroySeq(&Seq);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息