用C++实现简单的顺序表

来源:互联网 发布:淘宝搜索词查询在哪里 编辑:程序博客网 时间:2024/05/20 23:08

这周课后练习是实现老师上课的时候讲的顺序表的一些基本操作。我们用的是C语言的教材,但之前学计算机语言的时候学的是C++,虽然大家都说差不多,但对C语言的一些用法不太熟悉,还是尝试着用C++的语言来编写。代码如下:

#include<iostream>using namespace std;int y;struct Mylist{int list[20];int size;};void ListInitiate(Mylist &L){L.size = 0;}int ListLength(Mylist &L){return L.size;}void ListInsert(Mylist &L, int i, int x){int j;j = i;if (L.size >= 20)cout << "顺序表已满无法插入" << endl;else if (i<0 || i>L.size)cout << "参数i不合法!" << endl;else{for (j = L.size; j > i; j--){L.list[j] = L.list[j - 1];}L.list[i] = x;L.size++;cout << "数据" << x << "已插入第" << i << "个位置" << endl;}}void ListDelete(Mylist &L, int i){int j;if (L.size <= 0){cout << "顺序表已空无数据可删!" << endl;}else if (i<0 || i>L.size - 1)cout << "参数i不合法" << endl;else{y = L.list[i];for (j = i + 1; j < L.size; j++)L.list[j - 1] = L.list[j];L.size--;cout << "第"<<i<<"个位置的数据" << y << "已删除" << endl;}}void ListGet(Mylist &L, int i, int &x){if (i<0 || i>L.size - 1)cout << "参数i不合法" << endl;else{x = L.list[i];cout << "数据已提取" << endl;}}void ListShow(Mylist &L){cout << "顺序表中现有元素为:";for (int i = 0; i < L.size; i++)cout << L.list[i] << '\t';cout << endl;}void main(){int a, b, c, d, e;struct Mylist M;ListInitiate(M);cout << "顺序表M已生成,数据个数为0" << endl;while (1){cout << "插入元素按1,删除元素按2,取元素按3,展示现有元素按4,退出按5." << endl;cin >> c;if (c == 1){cout << "输入要插入元素和位置" << endl;cin >> a >> b;ListInsert(M, b, a);}else if (c == 2){cout << "输入要删除元素的位置" << endl;cin >> d;ListDelete(M, d);}else if (c == 3){cout << "输入要取元素的位置" << endl;cin >> e;ListGet(M, e, y);cout << "第" << e << "个位置的元素为" << y << endl;}else if (c == 4)ListShow(M);else if (c == 5)break;elsecout << "没有该选项" << endl;}}
老师上课讲的操作都写上了,但是就是写的好像太繁琐了,慢慢学习吧。

0 0