数据结构与算法作业0:顺序表的基本操作
【摘要】
有以下程序段,先改错,最后再编程实现所有函数的功能。
注:main()函数已给出,不得修改,提交时需要提交main函数。
#include<iostream.h>#include<stdlib.h>typedef int T class SeqList{private:T data;in...
有以下程序段,先改错,最后再编程实现所有函数的功能。
注:main()函数已给出,不得修改,提交时需要提交main函数。
-
#include<iostream.h>
-
#include<stdlib.h>
-
typedef int T
-
class SeqList
-
{
-
private:
-
T data;
-
int MaxSize; //顺序表最多可以存放的元素个数。
-
int last; //顺序表最后一个元素的下标,初始值为-1。
-
void SeqList(int sz);
-
void Input();//首先输入元素的个数,然后顺次输入元素的值。
-
void Output();//输出线性表的所有元素。
-
void Insert(const T& x, int i );//在线性表中第i个位置插入值为x的元素。
-
int Remove ( T & x );//从线性表中删除第一个值等于x的元素。
-
}
-
-
SeqList(int sz){data = new T[sz];MaxSize = sz; SeqList.last = -1; }
-
int main()
-
{
-
SeqList myList(100);
-
myList.Input();
-
myList.Output ();
-
int i;
-
for( i=0;i<5;i++)
-
myList.Insert(i+10,i);
-
myList.Output ();
-
for( i=10;i<15;i++)
-
myList.Remove(i);
-
myList.Output ();
-
-
return 0;
-
-
}
例如:
输入 | Result |
---|---|
5 1 2 3 4 5 |
The elements are: 1 2 3 4 5 The elements are: 10 11 12 13 14 1 2 3 4 5 The elements are: 1 2 3 4 5 |
4 4 3 2 1 |
The elements are: 4 3 2 1 The elements are: 10 11 12 13 14 4 3 2 1 The elements are: 4 3 2 1 |
我的答案:
-
#include<iostream>
-
#include<stdlib.h>
-
using namespace std;
-
-
typedef int T;
-
class SeqList
-
{
-
public:
-
T *data;
-
int MaxSize;
-
int last;
-
SeqList(int sz);
-
void Input();
-
void Output();
-
void Insert(const T & x,int i);
-
int Remove(T & x);
-
};
-
-
SeqList::SeqList(int sz)
-
{
-
MaxSize = sz;last = -1;
-
data = new T[sz];
-
}
-
-
void SeqList::Input()
-
{
-
int a;
-
cin>>a;
-
for(int i=0;i<a;i++)
-
{
-
cin>>data[i];
-
last++;
-
}
-
}
-
-
void SeqList::Output()
-
{
-
cout<<"The elements are:"<<endl;
-
for(int i=0;i<=last;i++)
-
{
-
-
cout<<data[i]<<endl;
-
}
-
}
-
-
void SeqList::Insert(const T & x,int i)
-
{
-
if(last == MaxSize-1)
-
{
-
cout<<"顺序表已无法插入"<<endl;
-
}
-
if(i<0||i>last+1)
-
{
-
-
cout<<"i越界"<<endl;
-
}
-
else
-
{
-
last++;
-
for(int j=last;j>i;j--)
-
data[j] = data[j-1];
-
data[i] = x;
-
}
-
-
}
-
-
int SeqList::Remove(T & x)
-
{
-
for(int i=0;i<=last;i++)
-
{
-
if(data[i]==x)
-
{
-
last--;
-
for(int j=i;j<=last;j++)
-
data[j] = data[j+1];
-
return 1;
-
}
-
}
-
return 0;
-
}
-
-
int main()
-
{
-
SeqList myList(100);
-
myList.Input();
-
myList.Output();
-
int i;
-
for(i=0;i<5;i++)
-
myList.Insert(i+10,i);
-
myList.Output();
-
for(i=10;i<15;i++)
-
myList.Remove(i);
-
myList.Output();
-
-
return 0;
-
}
文章来源: blog.csdn.net,作者:渣渣ye,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/yyfloveqcw/article/details/123757610
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)