增长数组的列表功能的实现

该程序的主要用于打破数组定长的限制,并实现增长数组的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;
}

下面是运行结果:
该程序的运行结果
通过分析运行结果,可知程序是正确的!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值