C语言数据结构顺序表的查找/插入/删除操作
<如题,没啥好说的,数据结构入门级的最基本操作>
展示效果在文末.
代码:
// 向顺序表插入一个元素x
struct Sqlist
{
int data[MAX_SIZE];
int length;
}sqlist;
void display(struct Sqlist *list, int length);
int insert(struct Sqlist *list, int p, int target);
int findpos(struct Sqlist L, int x);
int findval(struct Sqlist L, int x);
int delete(struct Sqlist *L, int p, int x);
int main(void)
{
sqlist.data[0] = 1;
sqlist.data[1] = 2;
sqlist.data[2] = 4;
sqlist.data[3] = 5;
sqlist.data[4] = 8;
sqlist.length = 5;
display(&sqlist, sqlist.length);
int x;
printf("请输入要插入的元素:\n");
scanf("%d", &x);
int p = findpos(sqlist, x);
sqlist.length = insert(&sqlist, p, x);
display(&sqlist, sqlist.length);
printf("请输入要删除的元素:\n");
scanf("%d", &x);
int q = findval(sqlist, x);
sqlist.length = delete(&sqlist, q, x);
display(&sqlist, sqlist.length);
return 0;
}
void display(struct Sqlist *list, int length)
{
for(int i = 0; i < length; i++)
{
printf("%d ", list->data[i]);
}
printf("\n");
}
int insert(struct Sqlist *list, int p, int target)
{
if(p < 0 || p > list->length || list->length == MAX_SIZE)
{
printf("插入失败\n");
return list->length;
}
for(int j = list->length-1; j >= p; --j)
{
list->data[j+1] = list->data[j];
}
list->data[p] = target;
return list->length+1;
}
int delete(struct Sqlist *L, int p, int x)
{
if(p < 0 || p >= L->length)
{
printf("删除失败\n");
return L->length;
}
else
{
for(int i = p; i < L->length-1; i++)
{
L->data[i] = L->data[i+1];
}
}
return L->length-1;
}
int findpos(struct Sqlist L, int x)
{
int i;
for(i = 0; i < L.length; ++i)
{
if(L.data[i] > x)
{
return i;
}
}
return i;
}
int findval(struct Sqlist L, int x)
{
int i;
for(i = 0; i < L.length; ++i)
{
if(L.data[i] == x)
{
return i;
}
}
return -1;
}
<效果展示>