当前位置:   article > 正文

【数据结构】顺序表_有两顺序表la 和lb,写一方法将他们合并成一个顺序表lc,要求lc的元素大小也是

有两顺序表la 和lb,写一方法将他们合并成一个顺序表lc,要求lc的元素大小也是

1.线性表

2.链表

顺序表

(1)运算实现

头文件:

  1. #ifndef LIST_H
  2. #define LIST_H
  3. const int maxlen = 100;//顺序表的最大存储长度
  4. template <class Type>
  5. class list {
  6. public:
  7. list();//构造函数初始化(C++11可以在类中初始化)
  8. void setlist();
  9. int length();//求顺序表当前长度
  10. void get_element(const int i, Type &x);//按序号取元素
  11. int locate(const Type x);//按元素取序号
  12. void insert(const int i, const Type x);//按序号插入元素
  13. void delete_element(const int i);//按序号删除元素
  14. void subset(const list<Type> A);//判断是否是A的子集
  15. private:
  16. Type data[maxlen];
  17. int count;
  18. };
  19. template <class Type>
  20. void list<Type>::setlist() {
  21. int x;
  22. cout << "输入序列:";
  23. while (cin >> x) {
  24. data[count] = x;
  25. ++count;
  26. }
  27. cin.clear();
  28. }
  29. template <class Type>
  30. list<Type>::list() {
  31. count = 0;
  32. }
  33. template <class Type>
  34. int list<Type>::length() {
  35. return count;
  36. }
  37. template <class Type>
  38. void list<Type>::get_element(const int i, Type &x) {
  39. if (i > 0 && i < count+1)
  40. x = data[i - 1];
  41. }
  42. template <class Type>
  43. int list<Type>::locate(const Type x) {
  44. for (int i = 0; i < count; ++i) {
  45. if (data[i] == x)
  46. return i + 1;
  47. }
  48. return -1;
  49. }
  50. template <class Type>
  51. void list<Type>::insert(const int i, const Type x) {
  52. if (count != maxlen) {
  53. if (i > 0 && i < count + 1) {
  54. for (int j = count - 1; (i - 1) <= j; --j)
  55. data[j + 1] = data[j];
  56. data[i - 1] = x;
  57. ++count;
  58. }
  59. }
  60. }
  61. template <class Type>
  62. void list<Type>::delete_element(const int i) {
  63. if (length() != 0) {
  64. if (i > 0 && i < count + 1) {
  65. for (int j = i + 1; j <= count; ++j)
  66. data[j - 2] = data[j - 1];
  67. --count;
  68. }
  69. }
  70. }
  71. template <class Type>
  72. void list<Type>::subset(list<Type> A) {
  73. int a;
  74. bool result;
  75. for (int i = 0; i < length(); ++i) {
  76. result = false;
  77. for (int j = 0; j < A.length(); ++j) {
  78. A.get_element(j, a);
  79. if (a == data[i]) {
  80. result = true;
  81. break;
  82. }
  83. }
  84. if (!result) {
  85. cout << "不是它的子集!" << endl;
  86. return;
  87. }
  88. }
  89. cout << "是它的子集!" << endl;
  90. }
  91. #endif

(2)应用实例

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

  源代码:

  1. #include<iostream>
  2. #include"list.h"
  3. using namespace std;
  4. int main() {
  5. int x;
  6. list<int> A, B;
  7. A.setlist();
  8. B.setlist();
  9. A.subset(B);
  10. cin.get();
  11. }
  运行截图:

                

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/876709?site
推荐阅读
相关标签
  

闽ICP备14008679号