用C++设置一个算法来解决有关顺序表的操作
要求:将程序用模板与类来编写。内容:(1)用C++设计顺序表的操作。
(2)顺序表的建立,初始化顺序表,清空顺序表 ,求顺序表的长度,检查顺序 表是否为空,检查顺序表是否为满。
(3)从顺序表中查找元素。
(4)更新顺序表中的给定元素 。
(5)向顺序表中插入元素。
(6)从顺序表中删除元素。
(7)遍历顺序表。
(8)对顺序表进行有序的输出。
要求:将程序用模板与类来编写。内容:(1)用C++设计顺序表的操作。
(2)顺序表的建立,初始化顺序表,清空顺序表 ,求顺序表的长度,检查顺序 表是否为空,检查顺序表是否为满。
(3)从顺序表中查找元素。
(4)更新顺序表中的给定元素 。
(5)向顺序表中插入元素。
(6)从顺序表中删除元素。
(7)遍历顺序表。
(8)对顺序表进行有序的输出。
答案:我这正好有一个,您看看能用吗。#include <iostream.h>
typedef int datatype;
const int maxsize= 20;
typedef struct{
datatype data[maxsize];
int last;
}sqlist;
class CList{
private:
sqlist L;
public:
void face();
void Init_list(int length);
void Insert_list(int whe, datatype x);
void Delete_list(int where);
int Select_list(datatype x);
};
void CList::face(){
cout<<"****欢迎试用顺序表****"<<endl;
cout<<"请输入要使用顺序表的长度:"<<endl;
}
void CList::Init_list(int length){
L.last=length;
for(int i=0; i<=L.last-1; i++){
cin>>L.data[i];
}
cout<<" 顺序表初始化完成"<<endl;
for(int j=0; j<=L.last-1;j++){
cout<<L.data[j]<<endl;
}
}
void CList::Insert_list(int a,datatype x){
for(int j=L.last-1; j>=a-1; j--)
L.data[j+1]=L.data[j];
L.data[a-1]=x;
L.last+=1;
cout<<"您插入的后的顺序表"<<endl;
for(int k=0; k<=L.last-1;k++)
cout<<L.data[k]<<endl;
}
void CList::Delete_list(int where){
for(int i=where;i<=L.last-1;i++)
L.data[i-1]=L.data[i];
L.last=L.last-1;
for(int j=0; j<=L.last-1;j++){
cout<<L.data[j]<<endl;
}
}
int CList::Select_list(datatype x){
for(int i=0; i<=L.last-1;i++){
if(x==L.data[i])
return i;
}}
void main(){
int length=0;
int xuhao;
CList list;
int where;
datatype what;
list.face();
cin>>length;
cout<<"请输入"<<length<<"个数据, 完成初始化"<<endl;
list.Init_list( length);
cout<<"请您输入所选操作的序号:";
cout<<"1:重新输入顺序表的值; "<<"2:插入数据; "<<"3删除数据; 4:搜索数据; 5:退出程序;"<<endl;;
cin>>xuhao;
while(1){
if(xuhao==1){
cout<<"请重新输入顺序表长度:"<<endl;
cin>>length;
list.Init_list( length);
}
else if(xuhao==2){
cout<<"请输入您要插入的位置, "<<endl;
cin>>where;
cout<<"请输入您要插入的数据, "<<endl;
cin>>what;
list.Insert_list(where , what);
}
else if(xuhao==3){
cout<<"请输入要删除数据的位置";
cin>>where;
list.Delete_list(where);
}
else if(xuhao==4){
datatype da;
cout<<"请输入要查找的数据";
cin>>da;
int whe=list.Select_list(da);
cout<<"位置是"<<whe+1<<endl;
}
else if(xuhao==5)
break;
cout<<"请您输入所选操作的序号:";
cout<<"1:重新输入顺序表的值; "<<"2:插入数据; "<<"3删除数据; 4:搜索数据; 5:退出程序;"<<endl;;
cin>>xuhao;
}
}你直接用vector吧
直接用vector就不符合题意了
思路不复杂,写起来还真费点时间呐,先定义一个结构吧,以int型为例:
struct mylist_st {
int value; //存放元素的值
mylist_st *next; //指向下一个元素的指针
}
class mylist {
private int count; //元素个数
private mylist_st *first; //第一个元素的指针
private mylist_st *last; //最后一个元素的指针
private reset(); //清除
mylist() { count=0; first=null; last=null;}
~mylist() { reset();}
......
}
上一个:C++培训机构哪里好?如何选择正确的IT培训机构?
下一个:注册码:Turbo C/C++ for windows 集成实验与学习环境,