c/c++实现一个基本的顺序表功能

#include <graphics.h>
#include <conio.h>
#include <stdio.h>
#include <string>
#include <iostream>

using namespace std;

#define MAX_SIZE	100

typedef struct 
{
	int *elems;	//顺序表的基址
	int length;	//顺序表的长度
	int size;	//顺序表的空间大小

}SqList;


bool initlist(SqList &L) //创建一个顺序表
{
	L.elems = new int[MAX_SIZE];	//分配MAX_SIZE大小的空间
	if (!L.elems)
	{
		return false;  //分配失败
	}
	L.length = 0;
	L.size = MAX_SIZE;
	return true;
}

void listprint(SqList& L) //打印顺序表元素
{
	cout << "顺序表的储存空间size;" << L.size << ",已保存的元素个数length:" << L.length << endl;
	for (int i = 0; i <=L.length-1; i++)
	{
		cout << L.elems[i]<<" ";
	}
	cout << endl;
}

bool listAppend(SqList& L, int e) //顺序表尾部添加元素
{
	if (L.length==L.size)
	{
		return false;
	}
	L.elems[L.length] = e;
	L.length++;
	return true;
}

bool listInsert(SqList& L, int i, int e)//i是插入的位置,在指定位置插入元素
{
	if (i<0||i>L.length)
	{
		return false;
	}
	if (L.length==L.size)
	{
		return false;
	}
	if ((L.length - 1) == i)
	{
		L.elems[L.length] = e;
		L.length++;
		return true;
	}
	for (int j = L.length-1 ; j >= i; j--)
	{
		L.elems[j + 1] = L.elems[j];
	}
	L.elems[i] = e;//将元素e放入i的位置
	L.length++;//表长加1

	return true;
}
bool listDelete(SqList& L, int i)//顺序表指定位置删除元素
{
	if (i<0|| i>=L.length)
	{
		return false;
	}
	if (i==L.length-1)
	{
		L.length--;
		return true;
	}
	for (int j = i; j < L.length-1; j++)
	{
		L.elems[j] = L.elems[j + 1];
	}
	L.length--;
	return true;
}

void destoryList(SqList& L) //顺序表销毁
{
	if (L.elems)
	{
		delete[] L.elems;
		L.length = 0;
		L.size = 0;
	}
}


int main()
{
	SqList list;
	int e;
	int i;

	cout << "初始化顺序表" << endl;
	if (initlist(list))
	{
		cout << "初始化顺序表成功!" << endl;
	}

	listprint(list);
	//添加元素
	int count = 0;
	cout << "请输入要添加的元素个数:" << endl;
	cin >> count;
	for (int i = 0; i < count; i++)
	{
		cout << "\n请输入要添加的元素:";
		cin >> e;
		if (listAppend(list,e))
		{
			cout << "添加成功!" << endl;
		}
		else
		{
			cout << "添加失败!" << endl;
		}
	}
	listprint(list);

	//插入元素

	cout << "请输入要插入的位置和要插入的数据元素:\n";
	cin >> i >> e;

	if (listInsert(list, i, e))
	{
		cout << "插入成功!" << endl;
	}
	else
	{
		cout << "插入失败!" << endl;
	}
	listprint(list);
	//删除元素
	cout << "请输入要删除元素的位置:";
	cin >> i;
	if (listDelete(list, i))
	{
		cout << "删除成功!" << endl;
	}
	else 
	{
		cout << "删除失败" << endl;
	}
	listprint(list);
	//销毁顺序表
	destoryList(list);

	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值