数据结构实验, 课程设计 代写联系Q1695161915
- 编写一个程序,实现顺序表的各种基本运算,在此基础上完成如下功能:
- 初始化顺序表L。
- 依次在顺序表L中插入元素a、b、c、e、f(从键盘输入数据)。
- 输出顺序表L。
- 输出顺序表L的长度。
- 输出顺序表L的第4个元素。
- 输出元素c的位置。
- 在第5个元素之前插入元素g。
- 输出顺序表L。
- 删除第3个元素。
- 输出顺序表L。
#include<iostream> #define maxsize 100 #define OK 1 #define ERROR 0 #define OVERFLOW -2 using namespace std; typedef char ElemType; typedef struct { ElemType *elem; int length; }Sqlist; char InitList(Sqlist &L)/*初始化顺序表*/ { L.elem = new ElemType[maxsize]; if (L.elem == NULL) { cout << "分配失败,退出程序!"; exit(OVERFLOW); } else L.length = 0; return OK; } int DeletList(Sqlist &L)/*删除顺序表中的元素*/ { int i, j; cout << "(9)请输入您要删除的元素所在的位置:"; cin >> i; if (i<1 || i>L.length) { cout << "输入数据不合法!"; return ERROR; } for (j = i; j <= L.length; j++) L.elem[j] = L.elem[j + 1]; --L.length; return 0; } void InsertList(Sqlist &L)/*向顺序表中输入元素*/ { int i, num; cout<<"(7)输入元素个数5,并依次在顺序表L中插入元素a、b、c、e、f(从键盘输入数据):"<<endl; cin >> num; L.length = num; for (i = 1; i <= num; i++)/*向顺序表中输入元素*/ cin >> L.elem[i]; } int InfixList(Sqlist &L)/*向顺序表中插入元素*/ { int i; ElemType item; cout << "(5)请输入您要插入的元素及其位置:"; cin >> item >> i; if (i < 1 || (i > L.length + 1) || L.length == maxsize) { cout << "输入的位置有误!"; return ERROR; } int j; for (j = L.length + 1; j >= i; j--) L.elem[j] = L.elem[j - 1]; L.elem[i] = item; ++L.length; return OK; } void PrintList(Sqlist L)/*输出顺序表中的元素*/ { int i; for (i = 1; i <= L.length; i++) cout << L.elem[i] << " "; cout << endl; } void search1(Sqlist L)/*查询指定位置的元素*/ { int i; cout << "(5)请输入您要查询的位置:"; cin >> i; cout << "您查询的元素为:" << L.elem[i] << endl; } void search2(Sqlist L)/*查询指定元素的位置*/ { int flag = 0; ElemType item; cout << "(6)请输入您要查询的元素:"; cin >> item; for (int i = 1; i <= L.length; i++) if (L.elem[i] == item) { cout << "您查询元素的位置为:" << i << endl; flag++; } if (flag == 0)cout << "未找到此元素!" << endl; } void LengthList(Sqlist L)/*输出顺序表的长度*/ { cout << "(4)顺序表的长度为:" << L.length<<endl; } int main() { Sqlist L; cout<<"(1)初始化顺序表L"<<endl; InitList(L);/*初始化*/ InsertList(L);/*输入元素*/ cout<<"(3)输出顺序表L:"; PrintList(L);/*输出元素*/ LengthList(L);/*输出顺序表的长度*/ search1(L);/*查询指定位置的元素*/ search2(L);/*查询指定元素的位置*/ InfixList(L);/*在指定位置i插入元素item*/ cout<<"(8)输出顺序表L:"; PrintList(L);/*输出元素*/ DeletList(L);/*删除元素*/ cout<<"(10)输出顺序表L:"; PrintList(L);/*输出顺序表*/ return 0; }
运行结果: