进行头插
eg:在数组 1 2 3 4 5的开头插入-1
变成-1 1 2 3 4 5
#include
typedef struct SeqList {
SLDataType a[100]; // 假设顺序表最大容量为100
int size; // 当前顺序表的大小
} SL;
void SeqListPushFront(SL* ps, SLDataType x)
{
int end = ps->size-1;
while (end >= 0) {
ps->a[end+1] = ps->a[end];
--end;
}
ps->a[0] = x;
ps->size++;
}
int main()
{
SL seqList; // 创建一个顺序表对象
seqList.size = 0; // 初始化顺序表的大小为0
// 向顺序表的开头插入元素
SeqListPushFront(&seqList, 10);
SeqListPushFront(&seqList, 20);
SeqListPushFront(&seqList, 30);
// 打印顺序表中的元素
for (int i = 0; i < seqList.size; i++) {
printf("%d ", seqList.a[i]);
}
printf("\n");
return 0;
}
头删
eg:数组1 2 3 4 5
删去1
#include
typedef struct SeqList {
SLDataType a[100];
int size;
} SL;
void SeqListRemoveFront(SL* ps)
{
if (ps->size <= 0) {
// 顺序表为空,无法进行头删操作
return;
}
for (int i = 0; i < ps->size - 1; i++) {
ps->a[i] = ps->a[i + 1];
}
ps->size--;
}
int main()
{
SL seqList;
seqList.size = 0;
// 添加一些元素到顺序表
seqList.a[0] = 10;
seqList.a[1] = 20;
seqList.a[2] = 30;
seqList.size = 3;
// 执行头删操作
SeqListRemoveFront(&seqList);
// 打印顺序表中的元素
for (int i = 0; i < seqList.size; i++) {
printf("%d ", seqList.a[i]);
}
printf("\n");
return 0;
}