该程序的主要用于打破数组定长的限制,并实现增长数组的List的部分功能。
这是头文件的代码:
#ifndef _ARRAY_H_
#define _ARRAY_H_
typedef int Elementtype;
struct List {
Elementtype* a;
int n;
int c;
};
void IsoutLitmit(List* p);
void AddAt(List* p, int index, Elementtype x);
void AddLast(List* p, Elementtype x);
void DeleteAt(List* p, int index);
void show(List* p);
#endif
头文件中有关函数的定义代码如下:
#include"Array.h"
#include<iostream>
#include<stdlib.h>
using namespace std;
void IsoutLitmit(List* p) {
if (p->n == p->c) {
Elementtype* temp = NULL;
temp = (Elementtype*)malloc(2 * p->c * sizeof(Elementtype));
for (int i = 0; i < p->n; i++) {
temp[i] = p->a[i];
}
p->c = 2 * p->c;
free(p->a);
p->a = temp;
}
else if (p->n < p->c)
return;
else {
printf("Error!\n");
return ;
}
}
void AddAt(List* p, int index, Elementtype x) {
IsoutLitmit(p);
for (int i = p->n; i > index; i--) {
p->a[i] = p->a[i - 1];
}
p->a[index] = x;
p->n++;
}
void AddLast(List* p, Elementtype x) {
IsoutLitmit(p);
p->a[p->n] = x;
p->n++;
}
void DeleteAt(List* p, int index) {
for (int i = index + 1; i < p->n; i++) {
p->a[i - 1] = p->a[i];
}
p->n--;
}
void show(List* p) {
cout << "The elements of Array are as follows:" << endl;
for (int i = 0; i < p->n; i++) {
cout << p->a[i] << " ";
}
printf("\n");
}
主函数的代码如下:
/*********************************************************************************************************************************************
由于数组的长度是有限制的,但该程序的主要用于打破数组定长的限制,并实现增长数组的List的部分功能
********************************************************************************************************************************************/
#include<iostream>
#include"Array.h"
#include<stdlib.h>
using std::cout;
using std::endl;
int main() {
List* pList = (List*)malloc(sizeof(List));
if (pList == NULL)
std::cout << "Memory allocation unseccessful!\n";
else {
pList->n = 0;
pList->c = 3;
pList->a =(Elementtype*)malloc(sizeof(Elementtype)*pList->c) ;
}
cout << "测试尾部添加函数Addlast功能" << endl;
AddLast(pList, 1);
AddLast(pList, 2);
AddLast(pList, 3);
show(pList);
cout << "测试判断是否需要扩容函数IsoutLitmit功能" << endl;
AddLast(pList, 4);
AddLast(pList, 5);
AddLast(pList, 6);
show(pList);
cout << "测试按下标添加函数AddAt功能" << endl;
AddAt(pList, 4, 7);
show(pList);
cout << "测试按下标删除函数DeleteAt功能" << endl;
DeleteAt(pList, 4);
show(pList);
return 0;
}
下面是运行结果:
通过分析运行结果,可知程序是正确的!