线性顺序表
#include<stdio.h>
#include<stdlib.h>
#define LIST_INIT_SIZE 100
#define LIST_INCREMENT 10
typedef char* Status;;
int *p, *q;
typedef struct {
int *elm;
int length;
int listsize;
}SqList;
void main() {
SqList List;
//输出
void out_put_list(SqList *L);
//创建一个顺序表
Status InitList_Sq(SqList *L);
//在第i个元素前的顺序表中插入数据
Status ListInsert_Sq(SqList*L, int i, int node);
//删除第I个元素
Status ListDelete_Sq(SqList *L, int i);
InitList_Sq(&List);
List.elm[0]= 2;//该方法和 *(Q.elm)=1是等价的
List.elm[1] = 3;
List.elm[2] = 4;
List.elm[3] = 5;
List.length = 4;
ListInsert_Sq(&List,1,1);
out_put_list(&List);
printf("----------------------\n");
ListDelete_Sq(&List, 3);
out_put_list(&List);
}
//创建一个空的顺序线性表
Status InitList_Sq(SqList *L) {
L->elm = (int *)malloc(LIST_INIT_SIZE*sizeof(int));
if (!L->elm)
{
printf("分配内存地址出错");
exit(0);
}
L->length = 0;
L->listsize =LIST_INIT_SIZE;
return "Ok";
}
//在线性表中的第i个元素前插入元素(i>=1)
Status ListInsert_Sq(SqList*L, int i,int node) {
int *newbase;
if (i<1 || i>(L->length+1)) {
return "ERROR";
}
//判断是否填满线性表的地址
if (L->length>=L->listsize) {
newbase = (int*)realloc(L->elm,(L->listsize+LIST_INCREMENT)*sizeof(int));
if (!newbase) {
exit(0);
}
L->elm = newbase;
L->listsize += LIST_INCREMENT;
}
//先保留 i-1的地址
p = &(L->elm[i - 1]);
//然后将i-1后面的地址进行加1(从最后一个元素开始)
for (q = &(L->elm[L->length - 1]); q >= p; --q) {
*(q + 1) = *q;
}
*p = node;
(L->length)++;
return "OK";
}
//删除第i个元素
Status ListDelete_Sq(SqList *L,int i) {
if (i<0 || i>(L->length - 1)) {
return "error";
}
p = &(L->elm[i - 1]);
for ( ; i <(L->length); i++)
{
*(p) =*(p + 1);
p++;
}
(L->length)--;
return "Ok";
}
//打印线性表中的数据
void out_put_list(SqList *L) {
for (int i = 0; i < (L->length);i++) {
printf("%d\n",L->elm[i]);
}
}