C++:顺序表的基本操作(待完善)

根据命令提示进行顺序表的基本操作(待完善)

#include<iostream>
#include<algorithm>
using namespace std;
#define MAXSIZE 1000
#define OVERFLOW -2
#define ERROR 1
typedef int ElemType;
typedef int Status;
typedef struct 
{
    ElemType* elem;
    int length;
}SqList;
void InitList(SqList& L)
{
    L.elem = new ElemType[MAXSIZE];
    if (L.elem == NULL)
    {
	cout << "存储空间分配失败!" << endl;
	exit(OVERFLOW);
    }
    L.length = 0;
    cout << "顺序表初始化完成" << endl;
}
void Create(SqList& L, int n, ElemType e) 
{
    cout << "请输入" << n << "个顺序表中的元素" << endl;
    for (int i = 0; i < n; i++) 
    {
	ElemType e;
	cin >> e;
	L.elem[i] = e;
	L.length++;
    }
}
int Print(SqList L)
{
    if (L.length == 0)
    {
	cout << "顺序表中无元素" << endl;
	return 1;
    }
    for (int k = 0; k < L.length; k++) 
    {
	if (k == L.length - 1)
	{
	    cout << L.elem[k];
	}
	else 
	{
	    cout << L.elem[k] << ' ';
	}
    }
}
int Insert(SqList& L, int i, ElemType e) 
{
    cout << "请输入要插入的元素及插得的位置" << endl;
    cin >> e >> i;
    if ((i < 1) || (i > L.length + 1)) 
    {
	cout << "插入地址不合法" << endl;
	return ERROR;
    }
    if (L.length == MAXSIZE) 
    {
	cout << "存储空间已满" << endl;
	return ERROR;
    }
    for (int j = L.length - 1; j >= i - 1; j--)
    {
	L.elem[j + 1] = L.elem[j];
    }
    L.elem[i - 1] = e;
    ++L.length;
}
int Delete(SqList& L, int i) {
    cout << "请输入要删除元素的位置" << endl;
    cin >> i;
    if((i < 1) || (i > L.length + 1))
    {
	cout << "删除地址不合法" << endl;
	return ERROR;
    }
    for (int j = i; j <= L.length; j++)
    {
	L.elem[j - 1] = L.elem[j];
    }
    --L.length;
}
void Sort(SqList& L) 
{
    sort(L.elem, L.elem + L.length);
}
int main() 
{
    int n, x,i=0,p=0;
    cout << "请输入数组长度n的值" << endl;
    cin >> n;
    SqList L;
    ElemType e=0;
    InitList(L);
    do
    {
	cout << "请选择您想进行的操作" << endl;
	cout << "0.给顺序表读入值" << endl;
	cout << "1.给顺序表插入值" << endl;
	cout << "2.给顺序表删除值" << endl;
	cout << "3.给顺序表排序" << endl;
	cout << "4.输出顺序表" << endl;
	cin >> x; 

	switch (x) {
	case 0: {
	    Create(L, n, e);
	    cout << "退出请按1,输入其他数字返回上级清单" << endl;
	    cin >> p;
	    break; }
	case 1: {
	    Insert(L, i, e);
	    cout << "退出请按1,输入其他数字返回上级清单" << endl;
	    cin >> p;
	    break;
	}
	case 2: {
	    Delete(L, i);
	    cout << "退出请按1,输入其他数字返回上级清单" << endl;
	    int p;
	    cin >> p;
	    break;
	}
	case 3: {
	    Sort(L);
	    cout << "退出请按1,输入其他数字返回上级清单" << endl;
	    cin >> p;
	    break;
	}
	case 4: {
	    Print(L);
	    cout << "退出请按1,输入其他数字返回上级清单" << endl;
	    cin >> p;
	    break;
	}
	}
    } while (p!=1);	  
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值