头文件
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
#define INIT 4
typedef int DataType;
struct str
{
DataType* a;
int size;
int quantity;
}s;
void Seqilstinit(struct str*);//初始化顺序表
void Seqilstprint(struct str*);//打印顺序表
void CheckCapacity(struct str*);//增容
void Seqilstpushback(struct str*,DataType);//尾插
void Seqilstpopback(struct str*);//尾删
void Seqilstpushhead(struct str*, DataType);//头插
void Seqilstpophead(struct str*);//头删
void SeqilstFind(struct str*,DataType);//查找
void SeqilstInsert(struct str*, size_t, DataType);//在pop位置插入x
void SeqilstErase(struct str*);//删除pop位置的值
void SeqiletDestory(struct str*);//销毁
函数实现
#include"head.h"
void Seqilstinit(struct str* p)//初始化
{
assert(p);
DataType* ps;
ps= (DataType*)realloc(p->a, sizeof(DataType) * INIT);//最初开辟四个空间
if (ps != NULL)
{
p->a = ps;
}
else
{
perror("raelloc");
exit(-1);
}
p->quantity = INIT;
p->size = 0;
}
void Seqilstprint(struct str* p)//打印
{
assert(p);
int i = 0;
for (i = 0; i < p->size; i++)
{
printf("%3d",p->a[i]);
}
}
void CheckCapacity(struct str* p)//扩容
{
assert(p);
if (p->quantity == p->size)
{
DataType* ps;
ps = (DataType*)realloc(p->a, sizeof(DataType) * 2 * (p->quantity));
if (ps != NULL)
{
p->a = ps;
}
p->quantity *= 2;
}
}
void Seqilstpushback(struct str* p, DataType x)//尾插
{
assert(p);
if (p->quantity == p->size)
{
CheckCapacity(p);
}
p->a[p->size] = x;
p->size++;
}
void Seqilstpopback(struct str* p)//尾删
{
p->size--;
}
void Seqilstpushhead(struct str* p,DataType x)//头插
{
int i=0;
CheckCapacity(p);
for (i =p->size-1; i>=0; i--)
{
p->a[i+1] = p->a[i];
}
p->a[0] =x;
p->size++;
}
void Seqilstpophead(struct str* p)//头删
{
assert(p);
int i=0;
for (i = 0; i < p->size; i++)
{
p->a[i] = p->a[i + 1];
}
p->size--;
}
void SeqilstFind(struct str* p, DataType x)//查找
{
assert(p);
DataType* b= &x;
DataType* ps=p->a ;
int i=0,c=0;
for (i =0; i < p->size; i++)
{
c=memcmp(ps,b,sizeof(DataType));
if (c == 0)
{
printf("%d在顺序表的第%d位\n", x,i+1);
}
ps++;
}
}
void SeqilstInsert(struct str * p, size_t pop, DataType x)//在pop位置插入x
{
int i=0;
CheckCapacity(p);
for (i = p->size - 1; i >= pop-1; i--)
{
p->a[i + 1] = p->a[i];
}
p->a[pop-1] = x;
p->size++;
}
void SeqilstErase(struct str* p,size_t pop)//删除pop位置的值
{
int i = 0;
for (i = pop-1; i < p->size; i++)
{
p->a[i] = p->a[i + 1];
}
p->size--;
}
void SeqiletDestory(struct str* p)//销毁
{
free(p->a);
p->a= NULL;
p->quantity = 0;
p->size = 0;
}