数据结构删除顺序表指定区域的数据(c语言)
要求:删除顺序表中x到y区间的所有数据,空间复杂度为O(1)
#include <stdio.h>
#include <stdlib.h>
#define MAX 20
typedef struct
{
int a[MAX];
int last=-1;//空表的值为-1,储存顺序表所储存最后元素的下标
}list;
void newList(list *l)
{
for (int i = 0; i < 10; i++)
{
l->a[i] = i;
}
l->last = 9;
}
void setList(list* l, int x, int y)
{
for (int i = 0; i < l->last + 1; i++)//遍历顺序表中的每一个数据
{
//如果满足删除的条件,就将该数据所在位置以后的数据统一向前移动一位,last值减一
if (l->a[i] > x && l->a[i] < y)
{
for (int j = i; j < l->last; j++)
{
l->a[j] = l->a[j + 1];
}
l->last--;
}
}
}
void printfList(list* l)
{
printf("该顺序表的内容是:\n");
for (int i = 0; i < l->last + 1; i++)
{
printf("%d\t", l->a[i]);
}
printf("\n");
}
int main()
{
list* l = (list*)malloc(sizeof(list));
newList(l);//创建顺序表
printfList(l);//输出旧表的数据
setList(l,1,3);//修改顺序表
printfList(l);//输出修改后的数据
return 0;
}