已知长度为n的线性表A采用顺序存储结构,请写一时间复杂度为O(n)、空间复杂度为O(1)的算法,该算法删除线性表中所有值为item的数据元素
【代码】已知长度为n的线性表A采用顺序存储结构,请写一时间复杂度为O(n)、空间复杂度为O(1)的算法,该算法删除线性表中所有值为item的数据元素。
·
#include<assert.h>
typedef int SXBint;
typedef struct SL
{
SXBint* a;
int size;
int capacity;
}SLnode;
void SeqLsitInit(SLnode* ps)
{
ps->a = NULL;
ps->capacity = ps->size = 0;
}
void kuorong(SLnode* ps)
{
if (ps->capacity == ps->size)
{
int Newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
SXBint* temp = (SXBint*)realloc(ps->a, sizeof(SLnode) * Newcapacity);
if (temp == NULL)
{
perror("error:");
exit(1);
}
ps->a = temp;
ps->capacity = Newcapacity;
}
}
void SeqPushback(SLnode* ps, SXBint x)
{
kuorong(ps);
ps->a[ps->size++] = x;
}
void Seq_dayin(SLnode ps)
{
for (int i = 0; i < ps.size; i++)
{
printf("%d->", ps.a[i]);
}
printf("NULL\n");
}
void deletes(SLnode* ps, int item) {
int j = 0;
for (int i = 0; i <= ps->size;i++) {
if (ps->a[i] != item)
{
ps->a[j] = ps->a[i];
++j;
}
}
ps->size = j - 1;
}
int main()
{
SLnode S;
SeqLsitInit(&S);
int n, num, item;
printf("请输入顺序表的长度\n");
scanf("%d", &n);
printf("请输入顺序表的元素\n");
for (int i = 0; i < n; i++)
{
scanf("%d", &num);
SeqPushback(&S, num);
}
printf("顺序表的元素如下\n");
Seq_dayin(S);
printf("请输入item的值\n");
scanf("%d", &item);
deletes(&S, item);
printf("删除item后\n");
Seq_dayin(S);
return 0;
}

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)