【数据结构】顺序表

顺序表的头文件以及应用
摘要由CSDN通过智能技术生成

1.线性表

2.链表

顺序表

(1)运算实现

头文件:

#ifndef LIST_H
#define LIST_H
const int maxlen = 100;//顺序表的最大存储长度

template <class Type>
class list {
public:
	list();//构造函数初始化(C++11可以在类中初始化)
	void setlist();
	int length();//求顺序表当前长度
	void get_element(const int i, Type &x);//按序号取元素
	int locate(const Type x);//按元素取序号
	void insert(const int i, const Type x);//按序号插入元素
	void delete_element(const int i);//按序号删除元素
	void subset(const list<Type> A);//判断是否是A的子集
private:
	Type data[maxlen];
	int count;
};

template <class Type>
void list<Type>::setlist() {
	int x;
	cout << "输入序列:";
	while (cin >> x) {
		data[count] = x;
		++count;
	}
	cin.clear();
}
template <class Type>
list<Type>::list() {
	count = 0;
}
template <class Type>
int list<Type>::length() {
	return count;
}
template <class Type>
void list<Type>::get_element(const int i, Type &x) {
	if (i > 0 && i < count+1)
		x = data[i - 1];
}
template <class Type>
int list<Type>::locate(const Type x) {
	for (int i = 0; i < count; ++i) {
		if (data[i] == x)
			return i + 1;
	}
	return -1;
}
template <class Type>
void list<Type>::insert(const int i, const Type x) {
	if (count != maxlen) {
		if (i > 0 && i < count + 1) {
			for (int j = count - 1; (i - 1) <= j; --j)
				data[j + 1] = data[j];
			data[i - 1] = x;
			++count;
		}
	}
}
template <class Type>
void list<Type>::delete_element(const int i) {
	if (length() != 0) {
		if (i > 0 && i < count + 1) {
			for (int j = i + 1; j <= count; ++j)
				data[j - 2] = data[j - 1];
			--count;
		}
	}
}
template <class Type>
void list<Type>::subset(list<Type> A) {
	int a;
	bool result;
	for (int i = 0; i < length(); ++i) {
		result = false;
		for (int j = 0; j < A.length(); ++j) {
			A.get_element(j, a);
			if (a == data[i]) {
				result = true;
				break;
			}
		}
		if (!result) {
			cout << "不是它的子集!" << endl;
			return;
		}
	}
	cout << "是它的子集!" << endl;
}
#endif

(2)应用实例

  假设顺序表A,B分别表示一个集合,设计算法判断A是否是B的子集

  源代码:

#include<iostream>
#include"list.h"
using namespace std;

int main() {
	int x;
	list<int> A, B;
	A.setlist();
	B.setlist();
	A.subset(B);
	cin.get();
}
  运行截图:

                

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值