#include<stdio.h>
#include<stdlib.h>
#define N 100
typedef struct
{
int a[N];
int last;
}seqlist_t;
/* 创建新表 */
seqlist_t* creatnewseqlist ()
{
seqlist_t* p = malloc(sizeof(seqlist_t)); //在堆区创建一个结构体返回首地址
if(p == NULL)
{
printf("goto bad\n");
return NULL;
}
p->last = 0; //数组有效值为0
return p;
}
/* 求表长 */
int getlenthline (seqlist_t* p)
{
return p->last;
}
/* 查找指定元素位置 */
int getplace (seqlist_t* p,int x)
{
int i;
for(i=0;i<p->last;i++)
{
if(x == p->a[i])
{
printf("%d在a[%d]\n",x,i);
return 0;
}
}
printf("不存在\n");
return -1;
}
/*清空表*/
void Emptyline (seqlist_t* p)
{
p->last = 0;
return ;
}
/* 判断是否为空 */
int isEmptyline (seqlist_t* p)
{
return p->last == 0;
}
/* 判断是否为满 */
int isFullline (seqlist_t* p)
{
return p->last == N ;
}
/* 插入新的数据 */
void insertintoline (seqlist_t* p,int post,int x)
{
int i;
if(post < 1 || post > p->last+1 || isFullline(p)) //插入判断
{
printf("插入失败\n");
return ;
}
for(i=p->last-1 ; i>=post-1 ; i--) //从后往前赋值直到增加的位置
{
p->a[i+1] = p->a[i];
}
p->a[post-1] = x;
p->last++;
}
/* 打印数组元素 */
void showline (seqlist_t* p)
{
int i;
for(i=0;i<p->last;i++)
{
printf("%d ",p->a[i]);
}
printf("\n");
}
/* 删除数组元素 */
void deleteline (seqlist_t* p,int post)
{
int i;
if(post < 1 || post > p->last || isEmptyline(p)) //从要删除的位置从前往后赋值
{
printf("删除失败\n");
return ;
}
for(i=post-1;i<p->last-1;i++)
{
p->a[i] = p->a[i+1];
}
p->last--;
}
int main(int argc, const char *argv[])
{
int i;
seqlist_t* s = creatnewseqlist();
for(i=0;i<5;i++)
{
s->a[i] = (i+1)*10+i+1 ;
s->last++;
}
showline(s);
insertintoline(s,1,666);
showline(s);
getplace(s,44);
getlenthline(s);
deleteline(s,1);
showline(s);
Emptyline(s);
return 0;
}
顺序存储(顺序表)
于 2022-04-06 20:42:27 首次发布