#include<iostream>
#include<string>
using namespace std;
#define MAXLEN 100
class Seqlist
{
public:
Seqlist(const Seqlist &a)
{
this->Last = a.Last;
for (int i = 0; i <= Last; i++)
{
this->arr[i] = a.arr[i];
}
}
Seqlist(int A[],int L)
{
for (int i = 0; i < L; i++)
{
this->arr[i] = A[i];
}
this->Last = L - 1;
}
Seqlist()
{
this->Last = -1;
}
void append(int i)
{
if (Last >= MAXLEN - 1)
{
cout << "数组已满,不可新增"<< endl;
return;
}
this->arr[this->Last + 1] = i;
Last++;
}
void show()
{
if (this->Last < 0)
{
cout << "顺序表为空"<< endl;
return;
}
for (int i = 0; i <= this->Last; i++)
{
cout << this->arr[i] << " ";
}
cout<<endl;
}
int size()
{
return this->Last + 1;
}
void Insert(int loac, int data)
{
//在位置为loac的位置插入data;
if (this->Last == MAXLEN - 1)
{
cout << "顺序表已满,不可插入"<< endl;
return;
}
if (loac > this->Last || loac < 0)
{
cout << "插入位置违法!" << endl;
return;
}
for (int i = Last; i >=loac; i--)
{
this->arr[i + 1] = this->arr[i];
}
this->arr[loac] = data;
this->Last++;
}
void Del(int loca)
{
//删除掉列表中第loca位置的数字
if (loca > this->Last || loca < 0)
{
cout << "插入位置越界" << endl;
return;
}
if (loca == this->Last)
{
this->Last--;
}
else
{
for (int i = loca+1; i <=this->Last; i++)
{
this->arr[i - 1] = this->arr[i];
}
this->Last--;
}
}
void find(int e)
{
if (this->Last < 0)
{
cout <<"链表为空" << endl;
return;
}
bool F_label = false;
for (int i = 0; i <= this->Last; i++)
{
if (this->arr[i] == e)
{
F_label = true;
cout << "找到位置为" << i << "的元素,其值为" << e << endl;
}
}
if (!F_label)
{
cout << "没有找到该元素"<< endl;
}
}
int arr[MAXLEN];
int Last;
};
Seqlist merge(Seqlist &a, Seqlist&b)
{
int a_point = 0;
int b_point = 0;
Seqlist c;
if (a.arr[a_point] <= b.arr[b_point])
{
c.append(a.arr[a_point]);
a_point++;
}
else
{
c.append(b.arr[b_point]);
b_point++;
}
while (a_point <= a.Last && b_point <= b.Last)
{
if (a.arr[a_point] <= b.arr[b_point])
{
c.append(a.arr[a_point]);
a_point++;
}
else
{
c.append(b.arr[b_point]);
b_point++;
}
}
while (a_point <= a.Last)
{
c.append(a.arr[a_point]);
a_point++;
}
while (b_point <= b.Last)
{
c.append(b.arr[b_point]);
b_point++;
}
return c;
}
void main()
{
int a[] = { 2,2,3 };
int b[] = { 1,3,3,4 };
Seqlist sq1(a, sizeof(a) / sizeof(int));
Seqlist sq2(b, sizeof(b) / sizeof(int));
sq1.show(); sq2.show();
Seqlist sq = merge(sq1, sq2);
cout << "合并之后的顺序表为:"<< endl;
sq.show();
sq2.find(3);
sq2.Del(2);
sq2.show();
sq2.Insert(2, 100);
sq2.show();
system("pause");
}
数据结构之顺序表C++实现
最新推荐文章于 2024-07-10 23:01:28 发布