一、插入
1.1静态分配下的插入操作
#include<iostream>
using namespace std;
#define MaxSize 10
typedef struct {
int data[MaxSize];
int length;
}SqlList;
void InitList(SqlList& L) {
for (int i = 0; i < MaxSize; i++)
L.data[i] = 0;
L.length = 0;
}
bool ListInsert(SqlList& L, int i, int e) {
if (i<1 || i>L.length + 1) return false;
if (L.length >= MaxSize) return false;
for (int j = L.length; j >= i; j--) {
L.data[j] = L.data[j - 1];
}
L.data[i - 1] = e;
L.length++;
return true;
}
int main() {
SqlList L;
InitList(L);
ListInsert(L, 1, 1);
ListInsert(L, 2, 2);
ListInsert(L, 3, 3);
ListInsert(L, 4, 4);
ListInsert(L, 5, 5);
for (int i = 0; i < L.length; i++)
cout << " " << L.data[i] << " ";
return 0;
}
1.2动态分配下的插入操作
#include<iostream>
using namespace std;
#define InitSize 10
typedef struct {
int* data;
int MaxSize;
int length;
}SeqList;
void InitList(SeqList& L) {
L.data = (int*)malloc(InitSize * sizeof(int));
L.length = 0;
L.MaxSize = InitSize;
}
void IncreaseSize(SeqList& L, int len) {
int* p = L.data;
L.data = (int*)malloc((L.MaxSize + len) * sizeof(int));
for (int i = 0; i < L.length; i++) {
L.data[i] = p[i];
}
L.MaxSize += len;
free(p);
}
bool ListInsert(SeqList& L, int i, int e) {
if (i<1 || i>L.length + 1) return false;
if (L.length > L.MaxSize) return false;
for (int j = L.length; j >= i; j--) {
L.data[j] = L.data[j - 1];
}
L.data[i - 1] = e;
L.length++;
return true;
}
int main() {
SeqList L;
InitList(L);
ListInsert(L, 1, 1);
ListInsert(L, 2, 2);
ListInsert(L, 3, 3);
ListInsert(L, 4, 4);
ListInsert(L, 5, 5);
for (int i = 0; i < L.length; i++)
cout << " " << L.data[i] << " ";
return 0;
}
|