赞
踩
1.线性表
2.链表
头文件:
- #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

假设顺序表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();
- }
运行截图:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。