【数据结构】问题 A: DS顺序表--类实现

【数据结构】问题 A: DS顺序表–类实现

题目描述

实现顺序表的用C++语言和类实现顺序表

属性包括:数组、实际长度、最大长度(设定为1000)

操作包括:创建、插入、删除、查找

类定义参考

输入

第1行先输入n表示有n个数据,即n是实际长度;接着输入n个数据
第2行输入要插入的位置和新数据
第3行输入要插入的位置和新数据
第4行输入要删除的位置
第5行输入要删除的位置
第6行输入要查找的位置
第7行输入要查找的位置

输出

数据之间用空格隔开

第1行输出创建后的顺序表内容,包括顺序表实际长度和数据

每成功执行一次操作(插入或删除),输出执行后的顺序表内容

每成功执行一次查找,输出查找到的数据

如果执行操作失败(包括插入、删除、查找等失败),输出字符串error,不必输出顺序表内容

-----------------

样例输入
6 11 22 33 44 55 66
3 777
1 888
1
9
0
5
样例输出
6 11 22 33 44 55 66
7 11 22 777 33 44 55 66
8 888 11 22 777 33 44 55 66
7 11 22 777 33 44 55 66
error
error
44

代码

#include <iostream>
using namespace std;
#define error -1
#define ok 1

class SeqList{
private:
	int *list;
	int maxsize;
	int size;

public:
	SeqList(){
		maxsize = 1000;
		size = 0;
		list = new int[maxsize];
	}
	~SeqList(){
		delete []list;
	}
	
	//输入n,以及n个数据 
	void InitList()
	{
		int n,e;
		
		cin>>n;
		if(n>=0 && n<=maxsize)
		{
			for(int i=0;i<n;i++)
			{
				cin>>e;
				size++;
				list[i]=e;
			}
		}
	}
	//插入
	int insertList(int pos,int elem)
	{
		if(pos<1 || pos>size+1)
		{
			return error;
		}
		for(int i=size-1;i>=pos-1;i--)
			list[i+1] = list[i];
		list[pos-1] = elem;
		size++;
		return ok; 
	}	
	//删除
	int deleteList(int pos)
	{
		if(pos<1 || pos>size)
		{
			return error;
		}
		for(int i=pos-1;i<size;i++)
			list[i] = list[i+1];
		size--;
		return ok;
	}
	//查找
	int  getList(int pos)
	{
		if(pos<1 || pos>size)
			return error;
		cout<<list[pos-1]<<endl;
		return ok;
	}
	
	//打印
	void printList()
	{
		cout<<size<<" ";
		for(int i=0;i<size;i++)
			cout<<list[i]<<" ";
		cout<<endl;
	 } 
};

int main()
{
	int pos,elem;
	
	SeqList L;
	//插入原始数据 
	L.InitList();
	L.printList();
	
	//插入数据
	cin>>pos>>elem;
	if( L.insertList(pos,elem)==1) 
		L.printList();
	else cout<<"error"<<endl;
	
	cin>>pos>>elem;
	if( L.insertList(pos,elem)==1) 
		L.printList();
	else cout<<"error"<<endl;
		
	//删除数据
	cin>>pos;
	if( L.deleteList(pos) ==1) 
		L.printList();
	else 
		cout<<"error" <<endl;
		
	cin>>pos;
	if( L.deleteList(pos) ==1) 
		L.printList();	
	else 
		cout<<"error" <<endl;
	//查找位置
	cin>>pos;
	if( L.getList(pos)==-1 ) 
		cout<<"error" <<endl;
	cin>>pos;
	if( L.getList(pos)==-1 ) 
		cout<<"error" <<endl;
	return 0;
}













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值