1.静态分配
#include<iostream> using namespace std; const int N = 10; typedef struct { int data[N]; int length; }SqList; void InitList(SqList &L) { for (int i = 0; i < N; i++) { L.data[i] = 0; } L.length = 0; } int main() { SqList L; InitList(L); return 0; }
2.动态分配
3.功能
#include<iostream> using namespace std; const int N = 10; typedef struct { int* data; int MaxSize; int length; }SqList; void InitList(SqList &L)//线性表的动态初始化 { int* data = (int*)malloc(N * sizeof(int)); int length=0; int MaxSize=N; } void IncreaseSize(SqList& L, int len)//增加线性表的长度 { L.data = (int*)malloc((N + len) * sizeof(int)); int* p = L.data; for (int i = 0; i < L.length; i++) { L.data[i] = p[i]; } L.MaxSize = N + len; free(p); } void Insert(SqList& L, int j, int e)//插入数据,在第i个位置上插入数值e { for (int i = L.length; i >= j; i--) { L.data[i] = L.data[i - 1]; } L.data[j - 1] = e; L.length++; } void del(SqList& L, int j)//删除第j个数据 { for (int i =j; i < L.length; i++) { L.data[i-1] = L.data[i]; } L.length--; } int main() { SqList L; InitList(L); IncreaseSize(L, 5); // ... return 0; }