盆友宇飞给我了道题,意识到自学还是干不过本科生。
下面是实现的代码:对循序表只是初相识了,甚至发现结构也运用得不是很熟练(根本不熟)。
#include <stdio.h>
/*自定义*/
#define MAX 6
typedef int elemtype;
/*自定义一个结构*/
typedef struct
{
elemtype List[MAX];
int num;
}qltype; /*qltype是一个结构名字*/
/*声明用到的函数*/
int listinsert(qltype*, int, elemtype );
int showlist(qltype*);
/*函数主体*/
int main()
{
qltype *L = NULL;
qltype Mylist = {{1, 2, 4, 5, 6}, 5}; /*定义时没有将List填满,留出3的空位*/
L = &Mylist;
listinsert(L, 3, 3);
showlist(L);
getchar();
return 0;
}
/*插入函数*/
int listinsert(qltype* L, int n, elemtype element) /*传入一个结构的指针, 插入的位置, 插入的元素*/
{
int key;
if (L -> num == MAX) /*如果顺序表已满*/
{
printf("the list is full");
return 0;
}
if (n < 1 || n > L -> num + 1) /*如果插入的位置不对*/
{
printf("check the number if in the range");
return 0;
}
if (n <= L -> num)
{
for (key = L -> num - 1; key >= n - 1; key--) /*key初始是List的最后一个元素, 一直到要插入的位置, 每次的key将前一个元素后移一位*/
{ /*即这里的循环操作是将插入位置之后的元素统一后移一位*/
L -> List[key + 1] = L -> List[key];
}
L -> List[n - 1] = element; /*将元素element插入在位置n上*/
L -> num++; /*顺序表长度+1*/
return 1;
}
}
/*显示顺序表中的元素*/
int showlist(qltype* L)
{
int i;
for (i = 0; i <= L -> num -1; i++)
{
printf("%d", L -> List[i]);
}
return 1;
}