顺序表:
顺序表的创建,初始化 InitList(Sqlist &L)
#include<stdio.h>
#define maxsize 10
//顺序表的创建(静态分配)
typedef struct {
int data[maxsize];
int length;
}Sqlist;
void Initlist (Sqlist &L)
{
for (int i = 0; i < maxsize; i++)
{
L.data[i] = 0;
L.length = 0;
}
}
int main()
{
Sqlist L;
Initlist(L);
return 0;
}
动态分配:创建;初始化;增加空间IncreaseSize
#include<stdlib.h>
#define initsize 10
typedef struct {
int* data;
int maxsize;
int length;
}Sqlist;
void Initlist(Sqlist &L)
{
L.data = (int*)malloc(initsize * sizeof(int));
L.length = 0;
L.maxsize = initsize;
}
void IncreaseSize(Sqlist& L, int a)
{
int* p = L.data;
L.data = (int*)malloc((L.maxsize + a) * sizeof(int));
for (int i = 0; i < L.maxsize; i++)
L.data[i] = p[i];
L.maxsize = L.maxsize + a;
free(p);
}
顺序表的插入(静态):ListInserrt()在第i个位置(位序)插入元素e;
bool Listinsert(Sqlist& L, int i, int e)
{
//合法性检测:i<1;i>length+1[当前尾部]l;i>maxsize;
if (i<1 || i>L.length + 1)
return false;
if (i > maxsize)
return false;
//从当前最后一个元素开始,每个元素往后移;
for (int j = L.length; j <= i; j--)
L.data[j + 1] = L.data[j];
L.data[i] = e;
L.length++;
return true;
}
顺序表的删除;ListDelect;在第i个位置的元素删除,并用e来返回该元素的值;
bool Listinsert(Sqlist& L, int i, int& e)
{
if (i<1 || i>L.length + 1)
return false;
if (i > maxsize)
return false;
e = L.data[i];
for (int j = i; j <=