#include<stdio.h>
#include<stdlib.h>
#define Max_num 100
typedef struct
{
int date[Max_num];
int length;//链表长度
}Seqit;
//创建空链表
Seqit* creatseqit()
{
Seqit* list = (Seqit*)malloc(sizeof(Seqit));
if (list == NULL) {
printf("内存分配失败\n");
exit(1); // 退出程序或进行错误处理
}
list->length = 0;
return list;
}
int isempty(Seqit* list)
{
return list->length == 0;
}
int isfull(Seqit* list)
{
return list->length == Max_num;
}
//插入元素
void insert(Seqit* list, int index, int element)//index 表示元素插入位置,element 表示插入元素
{
if (isfull(list))
{
printf("链表存储已到上限,无法再插入元素");
return;
}
if (index<0||index>list->length)
{
printf("插入位置违法,无法插入元素\n");
return;
}
for (int i = list->length; i > index; i--)
{
list->date[i] = list->date[i - 1];
}
list->date[index] = element;
list->length++;
}
//删除元素
void deletelist(Seqit* list, int index)
{
if (index < 0 || index >= list->length)
{
printf("删除位置违法,无法删除元素\n");
return;
}
for (int i = index; i < list->length; i++)
{
list->date[i] = list->date[i + 1];
}
list->length--;
}
//查找元素
void search(Seqit*list,int index)
{
if (index < 0 || index >= list->length)
{
printf("访问位置违法,无法获取元素\n");
return;
}
printf("%d ", list->date[index]) ;
}
//修改元素
void modify(Seqit* list, int index, int element)
{
if (index < 0 || index >= list->length)
{
printf("位置违法,无法修改元素\n");
return;
}
list->date[index] = element;
}
//打印链表
void show(Seqit* list)
{
int i = 0;
for (i = 0; i < list->length; i++)
{
printf("%d ", list->date[i]);
if (i < list->length - 1)printf(" ");
}
printf("\n");
}
int main()
{
Seqit* list = creatseqit();
insert(list ,0 ,10);
insert(list, 1, 20);
insert(list, 2, 30);
insert(list, 3, 40);
show(list);
deletelist(list, 1);
show(list);
search(list, 2);
printf("\n");
modify(list, 1, 50);
show(list);
free(list);
return 0;
}
代码完善空间还很大,欢迎各位提出建议,已经完成最基本的增删查改的功能。
加油!!!共勉!!!