#include <stdio.h>
#include <stdlib.h>
#define Error 0
#define Ok 1
#define OVERFLOW -1
#define List_Init_Size 10
#define LISTINCREMENT 5
typedef int ElemType;
typedef struct
{
ElemType *elem;
int listsize; /*线性表的长度*/
int length; /*当前元素个数*/
}SqList;
int InsertList(SqList *L, int i, ElemType e);
ShowList(SqList *L);
/*初始化线性表*/
int InitList(SqList *L)
{
L -> listsize = List_Init_Size;
L -> elem = (ElemType*)malloc(List_Init_Size*sizeof(ElemType));//将L.elem这个指针指向一块通过malloc函数分配的内存的地址
//这个内存的大小为Elemtype这个结构体的size*LIST_INIT_SIZE
//的乘积这么大 "malloc的语法是:指针名=(数据类型*)malloc
//(长度),(数据类型*)表示指针"
if(!L -> elem)
return OVERFLOW; //如果申请空间失败,则返回错误
L -> length = 0;
return Ok;
}
void DestroyList(SqList *L)
{
free(L); //释放malloc函数分配的内存空间
}
/*插入元素*/
int InputList(SqList *L)
{
int i, n = 10;
for(i = 1; i <= n; i++)
{
if(InsertList(L, i, i) != Ok)
{
break;
}
} ShowList(L);
return L -> length;
}
void IsEmptyList(SqList *L)
{
if(L -> length == 0)
printf( "It 's NULL/n ");
else
printf( "It 's not NULL/n ");
}
int InsertList(SqList *L, int i, ElemType e)
{
int j;
ElemType *temp;
if(i < 1 || i > L -> listsize + 1)
return Error; /*插入位置不合法*/
if(L -> length >= L -> listsize) /*追加空间*/
temp = (ElemType*)realloc(L -> elem, (L -> listsize + LISTINCREMENT)*sizeof(ElemType)); //LISTINCREMENT在前面分配的是5
if(!temp)
return OVERFLOW;
L -> elem = temp;/* = L -> elem;*/ //我修改过的
L -> listsize += LISTINCREMENT;
for(j = L -> length - 1; j >= i - 1; j--)
L -> elem[j + 1] = L -> elem[j];
L -> elem[i - 1] = e; /*插入元素 */
L -> length++;
return Ok;
}
int DeleList(SqList *L, int i, ElemType *e)
{
int j;
if(!IsEmptyList)
*e = L -> elem[i];
for(j = i; j <= L -> length; j++)
L -> elem[j-1] = L -> elem[j];
L -> length--;
return Ok;
}
ShowList(SqList *L)
{
int i;
for(i = 0; i < L -> length; i++)
{
printf("/n i = %d, e = %d ", i + 1, L -> elem[i]);
}
printf("/n ");
}
main()
{
SqList *L;
L = (SqList *)malloc(sizeof(SqList));
InitList(L);
L -> length = InputList(L);
InsertList(L, 1, 75);
ShowList(L);
DestroyList(L);
}