线性表的顺序表示是指用一组地址连续的存储单元依次存储线性表的数据元素。
随机存取的特性:用数组描述顺序存储结构
由于线性表的长度不定,采取动态分配的一维数组
type struct{
ElemType *elem;
int length;
int listsize;
}SqList;
线性表的几个操作:
1,InitList(&L)
初始化构造一个空的线性表
2,ListInsert(&L,i,e)
插入元素
3,ListDelete(&L,i,&e)
删除元素,用e返回
//完整代码:
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define OK 1
#define bool char
typedef struct{
int *elem; //存储空间基址
int length; //当前长度
int listsize; //当前分配的存储容量
}SqList;
int InitList_Sq(SqList *L){
//构造一个空的线性表
L->elem = (int *) malloc (LIST_INIT_SIZE * sizeof(int));
if(!L->elem)
exit(0);
L->length = 0;
L->listsize = LIST_INIT_SIZE;
return OK;
}
bool ListInsert(SqList *L,int i, int e)
{
int *q,*p;
if(i<1 || i>L->length+1 )
{
printf("i值不合法");
exit(0);
}
if(L->length > L->listsize)
{
int *newbase;
newbase = (int *) realloc (L->elem, (L->listsize+LISTINCREMENT)*sizeof(int));
if(!newbase)
exit(0);
L->elem = newbase;
L->listsize += LISTINCREMENT;
}
q = &(L->elem[i-1]);
for(p=&(L->elem[L->length-1]);p>=q;--p)
*(p+1) = *p;
*q = e;
++L->length;
return OK;
}
void ListDelete_Sq(SqList *L,int i,int *e)
{
//删除元素
int *p,*q;
if(i<1 || i>L->length)
exit(0);
p=&(L->elem[i-1]);
e = *p;
q = L->elem + L->length-1;
for(++p;p<=q;++p)
*(p-1) = *p;
--L->length;
}
int main()
{
SqList L;
int i,*e;
InitList_Sq(&L);
for(i=1;i<L.listsize;i++)
{
ListInsert(&L,i,i);
}
ListDelete_Sq(&L,10,&e);
for(i=1;i<L.length;i++)
printf("%d\n",L.elem[i]);
return 0;
}
注:根据严蔚敏的《数据结构》所写
采用C语言,课本中采用类C,引入了C++的引用,需要注意