关于数据结构中的 线性表(队列、栈)的相关讲解,请看
C++ 实现数据结构中的线性表
1.线性表的顺序存储的结构代码
typedef int ElementType;
#define Maxsize 10
struct Sequence
{
ElementType data[Maxsize];//存储数据的数组
int length;//线性表当前的长度
};
2.具体的方法实现,定义一个Sequence类
//head.h
typedef int Element_type;
#define Maxsize 10
#include<iostream>//必须加头文件
using namespace std;//必须加命名空间
class Sequence
{
private:
struct sequence
{
Element_type data[Maxsize];
int length;//此表中有数值的元素数量
};
sequence *x;//指向结构体(一个顺序表)的指针
public:
Sequence();
~Sequence(){delete x;}
Sequence(const Sequence &se);
Sequence &operator=(const Sequence &se);
void Insert(Element_type n, int i);
void Delete(int i);
friend ostream& operator<<(std::ostream&os, Sequence& se);
};
具体函数
//method.cpp
#include"head.h"
Sequence::Sequence()
{
x=new sequence;//创建一个顺序表,并用指针指向
for (int n = 0; n < Maxsize; n++)
x->data[n] = -1;//把数据初始化为-1
x->length = 0;
}
Sequence::Sequence(const Sequence &se)
{
x = new sequence;
for (int n = 0; n < se.x->length; n++)
this->x->data[n] = se.x->data[n];
this->x->length = se.x->length;
}
Sequence &Sequence::operator=(const Sequence &se)
{
x = new sequence;
for (int n = 0; n < se.x->length; n++)
this->x->data[n] = se.x->data[n];
this->x->length = se.x->length;
return *this;
}
void Sequence::Insert(Element_type n, int i)
{
if (this->x->length == Maxsize)
cout << "表满"<<endl;
if (i > this->x->length+1||i<1)
cout << "位置不合法"<<endl;
if (i<=this->x->length)//如果不是在表尾插入
{
for (int j = this->x->length - 1; j >= i-1; j--)
this->x->data[j + 1] = x->data[j];
}
//在表尾插入
this->x->data[i - 1] = n;
this->x->length++;
}
void Sequence::Delete(int i)//第i个位置,对应下标i-1
{
if (i > this->x->length)
cout << "此位置不存在"<<endl;
if (i < this->x->length)
{
for (int n = i; n < this->x->length; n++)
x->data[n - 1] = x->data[n];
}
this->x->length--;
}
ostream& operator<<(ostream& os, Sequence& se)
{
for (int n = 0; n < se.x->length; n++)
os << se.x->data[n] << endl;
return os;
}
主函数
//main.cpp
#include"head.h"
void main()
{
Sequence se;
for (int n = 1; n < 7; n++)
se.Insert(n, n);
se.Delete(6);
cout << se;
}