数据结构精选(一) 个人笔记 若有错误请谅解

绪论 

数据结构具体包含三个方面的内容:数据的逻辑结构,数据的储存结构,数据的操作算法

数据:数值数据 非数值数据

数据元素:组成数据的基本单位

数据对象:具有相同性质的数据元素的集合,是数据的子集

数据结构:数据元素及其相互关系的集合

数据类型:一组值的集合以及定义于这个值集上的一组操作的总称

程序=数据结构+算法

提高程序可读性的措施:模块化,变量,标识符含义化,注释,没设全局变量,空格和缩进

逻辑结构:

集合:数据元素属于同一个集合,但没有关系

线性结构:一对一

树结构:一对多

图结构:多对多

储存结构:顺序储存 链接储存

抽象数据类型:

ADT的定义:逻辑结构 操作集合

|

数据结构:储存结构 算法设计

|

类:成员变量 成员函数

算法:计算机求解特定问题的方法和步骤,是指令的有限序列

5个重要特性:

输入 输出 有穷性 确定性 可行性

算法的评价:正确性 健壮性 可读性 高效率 低储存空间需求

算法描述方法:自然语言 流程图 伪代码 程序设计语言

线性表:

特点:数据元素之间仅具有单一的前驱和后继关系,一个线性表中元素的类型必须相同

顺序表:插入 删除O(N)

对一个线性表分别进行遍历和逆置计算,最好的时间复杂度分别

  1. 遍历:
    • 时间复杂度:O(n)
    • 遍历线性表中的每个元素,需要访问每个元素一次,因此时间复杂度为O(n)。
  1. 逆置:
    • 时间复杂度:O(n)
    • 最优的逆置算法也需要访问线性表中的每个元素至少一次。一种常见的逆置方法是使用两个指针,分别从两端向中间移动,依次交换对应位置上的元素。这样的操作需要线性时间,因此时间复杂度也是O(n)。

链表:前插O(N) 后插O(1)

线性表可以用顺序表或链表存储,有 n个表同时并存,并且在处理过程中各表的长度会动态发生变化,表的总数也可能自动改变,应选用哪种存储表示,为什么

在处理过程中,线性表的长度会动态变化,并且表的总数也可能发生改变,这种情况下,应该选用链表存储表示。

下面是为什么选择链表存储表示的一些理由:

1. **动态长度

2. **动态总数:

3. **插入和删除效率高:

4. **不需要预先分配固定大小的内存空间:

5. **对内存的高效利用:

6. **容易实现动态扩展和收缩:

如果表的总数基本稳定,且很少进行插入和删除,但要求以最快的速度存取表中的元素,应采用哪种储存表示

如果表的总数基本稳定,且很少进行插入和删除操作,但要求以最快的速度存取表中的元素,那么应该选择使用顺序表作为存储表示。

以下是选择顺序表的一些理由:

1. **快速随机访问:*

2. **缓存友好:*

3. **节省内存:

4. **少量插入和删除操作不会带来太大影响:*

总的来说,如果你的应用场景中,表的总数基本稳定,而且对存取速度要求极高,同时又很少进行插入和删除操作,那么使用顺序表会更为合适。它能够提供快速的随机访问和较高的缓存友好性。

顺序表操作

  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. const int MAXsize = 100;//顺序表最大长度  
  5.   
  6. //PS:此实现中 顺序表下标从0开始!!  
  7.   
  8. class ssb  
  9. {  
  10. private:  
  11.     int data[MAXsize];  
  12.     int lenth;  
  13.   
  14. public:  
  15.   
  16.     ssb()//无参构造函数  
  17.     {  
  18.         lenth = 0;  
  19.     }  
  20.   
  21.     // 有参构造函数  
  22.     ssb(int arr[], int len)  
  23.     {  
  24.         if (len > MAXsize)  
  25.         {  
  26.             cout << "非法" << endl;  
  27.             return;  
  28.         }  
  29.         for (int i = 0; i < len; i++) data[i] = arr[i];  
  30.   
  31.         lenth = len;//储存真实长度  
  32.     }  
  33.   
  34.     int getlen()const// 获取顺序表长度  
  35.     {  
  36.         return lenth;  
  37.     }  
  38.   
  39.     //按位查找元素  
  40.     int findp(int pos)  
  41.     {  
  42.         if (pos<1 || pos>lenth)  
  43.         {  
  44.             cout << "查找位置超出范围" << endl;  
  45.             return -1;  
  46.         }  
  47.         return data[pos - 1];  
  48.     }  
  49.   
  50.     //按值查找  
  51.     int findv(int val)const  
  52.     {  
  53.         for (int i = 0; i < lenth; i++)  
  54.             if (data[i] == val) return i + 1;  
  55.   
  56.         cout << "未找到" << endl;  
  57.         return -1;  
  58.     }  
  59.   
  60.     // 遍历顺序表  
  61.     void tra()const  
  62.     {  
  63.         cout << "开始遍历" << endl;  
  64.         for (int i = 0; i < lenth; i++) cout << data[i] << " ";  
  65.   
  66.         cout << endl;  
  67.     }  
  68.   
  69.     // 插入元素,pos为插入位置(从1开始)  
  70.     void insert(int val, int pos)  
  71.     {  
  72.         if (pos<1 || pos>lenth + 1 || lenth == MAXsize)  
  73.         {  
  74.             cout << "非法" << endl;  
  75.             return;  
  76.         }  
  77.   
  78.         for (int i = lenth; i >= pos; i--) data[i] = data[i - 1];  
  79.   
  80.         data[pos - 1] = val;  
  81.         lenth++;  
  82.     }  
  83.   
  84.     // 删除元素,pos为删除位置(从1开始)  
  85.     void remove(int pos)  
  86.     {  
  87.         if (pos<1 || pos>lenth)  
  88.         {  
  89.             cout << "非法" << endl;  
  90.             return;  
  91.         }  
  92.   
  93.         for (int i = pos - 1; i < lenth - 1; i++) data[i] = data[i + 1];  
  94.   
  95.         lenth--;  
  96.     }  
  97.   
  98. };  
  99.   
  100. int main()  
  101. {  
  102.     int arr[] = { 1, 2, 3, 4, 5 };  
  103.     int len = sizeof(arr) / sizeof(arr[0]);  
  104.   
  105.     ssb l1;  
  106.     ssb l2(arr, len);  
  107.   
  108.     cout << "2" << l2.getlen() << endl;  
  109.     cout << l2.findp(3) << endl;  
  110.     cout << l2.findv(4) << endl;  
  111.     l2.tra();  
  112.     l2.insert(6, 2);  
  113.     l2.tra();  
  114.     l2.remove(4);  
  115.     l2.tra();  
  116.   
  117.     return 0;  
  118. }  

单链表操作

  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. struct node  
  5. {  
  6.     int data;  
  7.     node* next;  
  8.   
  9.     node(int val):data(val),next(nullptr){}  
  10. };  
  11.   
  12. class lb  
  13. {  
  14. private:  
  15.     node* head;  
  16.   
  17. public:  
  18.   
  19.     //无参构造  
  20.     lb() :head(nullptr) {}  
  21.   
  22.     //有参构造  
  23.     lb(int arr[], int n)  
  24. {
  25.         head = nullptr;//初始化头指针为空  
  26.         for (int i = n - 1; i>= 0; i--)  
  27.         {  
  28.             //逆序插入元素 保证与原序列顺序一致  
  29.             node* newn = new node(arr[i]);  
  30.             newn->next = head;  
  31.             head = newn;  
  32.         }  
  33.     }  
  34.   
  35.     //析构  
  36.     ~lb()  
  37.     {  
  38.         node* temp;  
  39.         while (head != nullptr)  
  40.         {  
  41.             temp = head;  
  42.             head = head->next;  
  43.             delete temp;  
  44.         }  
  45.     }  
  46.   
  47.     //遍历输出  
  48.     void tra()  
  49.     {  
  50.         node* cur = head;  
  51.         while (cur != nullptr)  
  52.         {  
  53.             cout << cur->data << " ";  
  54.             cur = cur->next;  
  55.         }  
  56.         cout << endl;  
  57.     }  
  58.   
  59.     //按位查找  
  60.     node* findp(int pos)  
  61.     {  
  62.         if (pos <= 0) return nullptr;  
  63.         node* cur = head;  
  64.         for (int i = 1; i < pos && cur != nullptr; i++) cur = cur->next;  
  65.         return cur;  
  66.     }  
  67.   
  68.     //按值查找  
  69.     node* findv(int val)  
  70.     {  
  71.         node* cur = head;  
  72.         while (cur != nullptr)  
  73.         {  
  74.             if (cur->data == val) return cur;  
  75.             cur = cur->next;  
  76.         }  
  77.         return nullptr;  
  78.     }  
  79.   
  80.     //在指定位置前插  
  81.     void qc(int pos, int val)  
  82.     {  
  83.         if (pos <= 0) return;  
  84.         node* newn = new node(val);  
  85.         if (pos == 1)  
  86.         {  
  87.             //在头部插入 要特判  
  88.             newn->next = head;  
  89.             head = newn;  
  90.         }  
  91.         else  
  92.         {  
  93.             node* cur = head;  
  94.             for (int i = 1; i < pos - 1 && cur != nullptr; i++) cur = cur->next;  
  95.             if (cur != nullptr)  
  96.             {  
  97.                 newn->next = cur->next;  
  98.                 cur->next = newn;  
  99.             }  
  100.             else// 如果指定位置超出链表长度,直接在尾部插入  
  101.             {  
  102.                 node* tail = head;  
  103.                 while (tail->next != nullptr) tail = tail->next;  
  104.                 tail->next = newn;  
  105.             }  
  106.         }  
  107.     }  
  108.   
  109.     //在指定位置后插  
  110.     void hc(int pos, int val)  
  111.     {  
  112.         if (pos <= 0) return;  
  113.         node* newn = new node(val);  
  114.         if (pos == 1)  
  115.         {  
  116.             newn->next = head;  
  117.             head = newn;  
  118.         }  
  119.         else  
  120.         {  
  121.             node* cur = head;  
  122.             for (int i = 1; i < pos && cur != nullptr; i++) cur = cur->next;  
  123.             if (cur != nullptr)  
  124.             {  
  125.                 newn->next = cur->next;  
  126.                 cur->next = newn;  
  127.             }  
  128.         }  
  129.     }  
  130.   
  131.     //删除指定位置结点  
  132.     void de(int pos)  
  133.     {  
  134.         if (pos <= 0) return;  
  135.         if (pos == 1)  
  136.         {  
  137.             node* tem = head;  
  138.             head = head->next;  
  139.             delete tem;  
  140.         }  
  141.         else  
  142.         {  
  143.             node* cur = head;  
  144.             for (int i = 1; i < pos - 1 && cur != nullptr; i++) cur = cur->next;  
  145.             if (cur != nullptr && cur->next != nullptr)  
  146.             {  
  147.         node* pre = nullptr;  
  148.         node* cur = head;  
  149.         node* ne = nullptr;  
  150.         while (cur != nullptr)  
  151.         {  
  152.             ne = cur->next;  
  153.             cur->next = pre;  
  154.             pre = cur;  
  155.             cur = ne;  
  156.         }  
  157.         head = pre;  
  158.     }  
  159.   
  160.     //有序合并单链表  
  161.     void merge(lb& list)  
  162.     {  
  163.         node* m = nullptr;//合并后的链表头指针,初始为 nullptr  
  164.         node* cur = head;//当前链表(调用函数的链表)的指针,初始为该链表的头指针  
  165.         node* oth = list.head;//另一链表的指针,初始为另一链表的头指针  
  166.         node* mcur = nullptr;//合并链表的当前指针,初始为 nullptr  
  167.   
  168.         while (cur != nullptr || oth != nullptr)  
  169.         {  
  170.             node* newn = new node(0);  
  171.             if (m == nullptr)  
  172.             {  
  173.                 m = newn;  
  174.                 mcur = m;  
  175.             }  
  176.             else  
  177.             {  
  178.                 mcur->next = newn;  
  179.                 mcur = mcur->next;  
  180.             }  
  181.             if (cur != nullptr && (oth == nullptr || cur->data <= oth->data))  
  182.             {  
  183.                 newn->data = cur->data;  
  184.                 cur = cur->next;  
  185.             }  
  186.             else if (oth != nullptr)  
  187.             {  
  188.                 newn->data = oth->data;  
  189.                 oth = oth->next;  
  190.             }  
  191.         }  
  192.         //释放原链表内存  
  193.         node* tem;  
  194.         while (head != nullptr)  
  195.         {  
  196.             tem = head;  
  197.             head = head->next;  
  198.             delete tem;  
  199.         }  
  200.         head = m;  
  201.     }  
  202. };  
  203.   
  204. int main()   
  205. {  
  206.     int arr1[] = { 1, 3, 5, 7, 9 };  
  207.     int arr2[] = { 2, 4, 6, 8, 10 };  
  208.   
  209.     lb l1(arr1, 5);  
  210.     lb l2(arr2, 5);  
  211.   
  212.     l1.tra();  
  213.     l2.tra();  
  214.   
  215.     l1.merge(l2);  
  216.     l1.tra();  
  217.   
  218.     l1.reverse();  
  219.     l1.tra();  
  220.   
  221.     l1.qc(2, 19);// 在位置2前插入  
  222.     l1.tra();  
  223.     l1.hc(4, 60); // 在位置4后插入  
  224.     l1.tra();  
  225.   
  226.     l1.de(3);// 删除节点3  
  227.     l1.tra();  
  228.   
  229.     return 0;  
  230. }  

//双向链表

  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. class node  
  5. {  
  6. public:  
  7.     int data;  
  8.     node* pre;  
  9.     node* next;  
  10.   
  11.     node(int val):data(val),pre(nullptr),next(nullptr){}  
  12. };  
  13.   
  14. class slb  
  15. {  
  16. private:  
  17.     node* head;  
  18. public:  
  19.     slb() :head(nullptr) {};  
  20.   
  21.     slb(int arr[], int n)  
  22.     {  
  23.         head = nullptr;  
  24.         for (int i = 0; i < n; i++)  
  25.         {  
  26.             node* newn = new node(arr[i]);
  27.             if (head == nullptr) head = newn;  
  28.             else  
  29.             {  
  30.                 node* cur = head;  
  31.                 while (cur->next != nullptr) cur = cur->next;  
  32.                 cur->next = newn;  
  33.                 newn->pre = cur;  
  34.             }  
  35.         }  
  36.     }  
  37.   
  38.     //求链表长度  
  39.     int getlen()const  
  40.     {  
  41.         int cou = 0;  
  42.         node* cur = head;  
  43.         while (cur != nullptr)  
  44.         {  
  45.             cou++;  
  46.             cur = cur->next;  
  47.         }  
  48.         return cou;  
  49.     }  
  50.   
  51.     int finp(int pos) const  
  52.     {  
  53.         if (pos <= 0)  
  54.         {  
  55.             cout << "非法" << endl;  
  56.             return -1;  
  57.         }  
  58.         node* cur = head;  
  59.         for (int i = 1; i < pos && cur != nullptr; i++) cur = cur->next;  
  60.         if (cur != nullptr) return cur->data;  
  61.         else  
  62.         {  
  63.             cout << "越界" << endl;  
  64.             return -1;  
  65.         }  
  66.     }  
  67.   
  68.     int finv(int val)const  
  69.     {  
  70.         node* cur = head;  
  71.         int pos = 1;  
  72.         while (cur != nullptr)  
  73.         {  
  74.             if (cur->data == val) return pos;  
  75.             cur = cur->next;  
  76.             pos++;  
  77.         }  
  78.         cout << "没找到" << endl;  
  79.         return -1;  
  80.     }  
  81.   
  82.     void tra()const  
  83.     {  
  84.         node* cur = head;  
  85.         while (cur != nullptr)  
  86.         {  
  87.             cout << cur->data << " ";  
  88.             cur = cur->next;  
  89.         }  
  90.         cout << endl;  
  91.     }  
  92.   
  93.     void qc(int pos, int val)  
  94.     {  
  95.         if (pos <= 0)  
  96.         {  
  97.             cout << "非法" << endl;  
  98.             return;  
  99.         }  
  100.         node* newn = new node(val);  
  101.         if (pos == 1)  
  102.         {  
  103.             newn->next = head;  
  104.             head->pre = newn;  
  105.             head = newn;  
  106.         }  
  107.         else  
  108.         {  
  109.             node* cur = head;  
  110.             for (int i = 1; i < pos - 1 && cur != nullptr; i++) cur = cur->next;  
  111.             if (cur != nullptr)  
  112.             {  
  113.                 newn->next = cur->next;  
  114.                 newn->pre = cur;  
  115.                 cur->next->pre = newn;  
  116.                 cur->next = newn;  
  117.             }  
  118.         }  
  119.     }  
  120.   
  121.     void hc(int pos, int val)  
  122.     {  
  123.         if (pos <= 0)  
  124.         {  
  125.             cout << "非法" << endl;  
  126.             return;  
  127.         }  
  128.         node* newn=new node(val);  
  129.         if (pos == 1)  
  130.         {  
  131.             newn->next = head;  
  132.             head->pre = newn;  
  133.             head = newn;  
  134.         }  
  135.         else  
  136.         {  
  137.             node* cur = head;  
  138.             for (int i = 1; i < pos && cur != nullptr; i++) cur = cur->next;  
  139.             if (cur != nullptr)  
  140.             {  
  141.                 newn->next = cur->next;  
  142.                 newn->pre = cur;  
  143.                 cur->next->pre = newn;  
  144.                 cur->next = newn;  
  145.             }  
  146.         }  
  147.     }  
  148.   
  149.     void de(int val)  
  150.     {  
  151.         node* cur = head;  
  152.         while (cur != nullptr && cur->data != val) cur = cur->next;  
  153.         if (cur == nullptr)  
  154.         {  
  155.             cout << "没找到" << endl;  
  156.             return;  
  157.         }  
  158.         if (cur->pre == nullptr)  
  159.         {  
  160.             //删除头结点  
  161.             head = cur->next;  
  162.             if (head != nullptr) head->pre = nullptr;  
  163.         }  
  164.         else  
  165.         {  
  166.             cur->pre->next = cur->next;  
  167.             cur->next->pre = cur->pre;  
  168.         }  
  169.         delete cur;  
  170.     }  
  171.   
  172.     void rev()  
  173.     {  
  174.         node* tem = nullptr;  
  175.         node* cur = head;  
  176.         while (cur != nullptr)  
  177.         {  
  178.             tem = cur->pre;  
  179.             cur->pre = cur->next;  
  180.             cur->next = tem;  
  181.             cur = cur->pre;  
  182.         }  
  183.         if (tem != nullptr) head = tem->pre;  
  184.     }  
  185.   
  186.     ~slb()  
  187.     {  
  188.         node* tem;  
  189.         while (head != nullptr)  
  190.         {  
  191.             tem = head;  
  192.             head = head->next;  
  193.             delete tem;  
  194.         }  
  195.     }  
  196. };  
  197.   
  198. int main()  
  199. {  
  200.     // 创建双向链表  
  201.     int arr[] = { 1, 2, 3, 4, 5 };  
  202.     slb l1 = slb(arr, 5);  
  203.     l1.tra();  
  204.   
  205.     l1.qc(3, 6);  
  206.     l1.tra();  
  207.     l1.hc(5, 7);  
  208.     l1.tra();  
  209.   
  210.     l1.de(4);  
  211.     l1.tra();  
  212.   
  213.     l1.rev();  
  214.     l1.tra();  
  215.   
  216.     return 0;  
  217.   
  218. }  

求并集

  1. #include<iostream>  
  2. #include<unordered_set>  
  3. #include<vector>  
  4. using namespace std;  
  5.   
  6.   
  7. class set  
  8. {  
  9. private:  
  10.     vector<int>ele;  
  11. public:  
  12.   
  13.     // 添加元素到集合  
  14.     void add(int e)  
  15.     {  
  16.         ele.push_back(e);  
  17.     }  
  18.   
  19.     // 获取集合元素  
  20.     vector<int>get()const  
  21.     {  
  22.         return ele;  
  23.     }  
  24.   
  25.     // 判断集合是否包含某个元素  
  26.     bool contain(int e)const  
  27.     {  
  28.         for (int x : ele)  
  29.             if (x == e) return true;  
  30.         return false;  
  31.     }  
  32.   
  33.     // 计算集合并集  
  34.     set uni(const set& s)const  
  35.     {  
  36.         set uniset= *this;//创建一个新的集合 unionSet,并将当前集合 *this 的所有元素复制到 unionSet 中。  
  37.         //这样做是为了保留当前集合的所有元素,形成一个初始的并集  
  38.         for (int e : s.get())//遍历第二个集合 set2 中的所有元素  
  39.             if (!contain(e)) uniset.add(e);  
  40.   
  41.         return uniset;  
  42.     }  
  43.   
  44. };  
  45.   
  46. int main()  
  47. {  
  48.     set s1, s2;  
  49.     s1.add(1);  
  50.     s1.add(2);  
  51.     s1.add(3);   
  52.     s1.add(4);  
  53.     s1.add(5);  
  54.   
  55.     s2.add(3);  
  56.     s2.add(4);  
  57.     s2.add(5);  
  58.     s2.add(6);  
  59.     s2.add(7);  
  60.   
  61.     set unis = s1.uni(s2);  
  62.     for (int x : unis.get())  
  63.         cout << x << " ";  
  64.   
  65.     return 0;  
  66. }  

2

  1. #include<iostream>  
  2. #include<unordered_set>  
  3. #include<vector>  
  4. using namespace std;  
  5.   
  6. unordered_set<int>uni(const unordered_set<int>& s1, const unordered_set<int>& s2)  
  7. {  
  8.     unordered_set<int>uniset = s1;  
  9.     for (int x : s2) uniset.insert(x);  
  10.   
  11.     return uniset;  
  12. }  
  13. int main()  
  14. {  
  15.     unordered_set<int>s1 = { 1,2,3,4,5 };  
  16.     unordered_set<int>s2 = { 3,4,5,6,7 };  
  17.   
  18.     unordered_set<int>re = uni(s1, s2);  
  19.   
  20.     for (int x : s1) cout << x << " ";  
  21.     cout << endl;  
  22.   
  23.     for (int x : s2) cout << x << " ";  
  24.     cout << endl;  
  25.   
  26.     for (int x : re) cout << x << " ";  
  27.     cout << endl;  
  28.   
  29.  }  

一元多项式相加

  1. #include<iostream>  
  2. #include<map>  
  3. using namespace std;  
  4.   
  5. using  poly=map<intdouble>;//使用 C++ 中的 using 关键字为 std::map<int, double> 定义了一个别名   
  6.   
  7. poly add(const poly& p1, const poly& p2)  
  8. {  
  9.     poly re;  
  10.   
  11.     for (const auto& t : p1)  re[t.first] += t.second;  
  12.     for (const auto& t : p2)  re[t.first] += t.second;  
  13.   
  14.     return re;  
  15. }  
  16.   
  17. void print(const poly& p)  
  18. {  
  19.     for (const auto& t : p)  
  20.         cout << t.second << "x^" << t.first << "+";  
  21.     cout << "0" << endl;  
  22. }  
  23.   
  24. int main()  
  25. {  
  26.      poly p1 = { {2, 3.5}, {1, 2.0}, {0, 1.0} };  
  27.      poly p2 = { {2, 1.5}, {1, 3.0}, {0, 2.0} };  
  28.   
  29.      poly re = add(p1, p2);  
  30.   
  31.      print(p1);  
  32.      print(p2);  
  33.      print(re);  
  34.   
  35.      return 0;  
  36. }  

将元素为整数的顺序表重新排列以a1为界的两部分,a1前面的值均比a1小,a1后面的值都比a1大,要求算法时间复杂度O(n)

荷兰国旗问题是一种经典的数组排序问题,其中数组中的元素只有三种不同的值。这个问题的目标是将数组按照这三种值分为三个部分,实现排序。这个问题的名字来自于荷兰国旗的颜色有三种,与数组元素的三种值相对应。

  1. #include <iostream>  
  2. #include <vector>  
  3. /*算法步骤如下: 
  4.  
  5. 初始化三个指针:low指向表头,high指向表尾,mid指向当前遍历的元素。 
  6.  
  7. 开始遍历列表: 
  8.  
  9. 如果arr[mid] < a1,将arr[mid]arr[low]交换,然后lowmid同时向后移动。 
  10. 如果arr[mid] > a1,将arr[mid]arr[high]交换,然后high向前移动。 
  11. 如果arr[mid] == a1,只需将mid向后移动。 
  12. 重复上述步骤直到mid指向表尾。*/   
  13. void rearrange(std::vector<int>& arr, int a1) {  
  14.     int low = 0;  
  15.     int high = arr.size() - 1;  
  16.     int mid = 0;  
  17.   
  18.     while (mid <= high) {  
  19.         if (arr[mid] < a1) {  
  20.             std::swap(arr[low], arr[mid]);  
  21.             low++;  
  22.             mid++;  
  23.         } else if (arr[mid] > a1) {  
  24.             std::swap(arr[mid], arr[high]);  
  25.             high--;  
  26.         } else {  
  27.             mid++;  
  28.         }  
  29.     }  
  30. }  
  31.   
  32. int main() {  
  33.     std::vector<int> arr = {3, 1, 5, 2, 6, 4, 7};  
  34.     int a1 = 4;  
  35.   
  36.     rearrange(arr, a1);  
  37.   
  38.     for (int i : arr) {  
  39.         std::cout << i << " ";  
  40.     }  
  41.     std::cout << std::endl;  
  42.   
  43.     return 0;  
  44. }  

编写算法,求循环链表中结点个数

  1. #include <iostream>  
  2.   
  3. // 定义循环链表的结点结构  
  4. struct ListNode {  
  5.     int val;  
  6.     ListNode* next;  
  7.     ListNode(int x) : val(x), next(NULL) {}  
  8. };  
  9.   
  10. // 计算循环链表中结点的个数  
  11. int countNodesInCircularLinkedList(ListNode* head) {  
  12.     if (head == NULL) {  
  13.         return 0; // 如果链表为空,则节点个数为0  
  14.     }  
  15.   
  16.     ListNode* current = head; // 从头结点开始遍历  
  17.     int count = 0; // 初始化计数器为0  
  18.   
  19.     do {  
  20.         count++;  
  21.         current = current->next; // 移动到下一个结点  
  22.     } while (current != head); // 当遍历回到头结点时停止循环  
  23.   
  24.     return count  

已知一个单链表,请编写复制单链表的算法

  1. #include <iostream>  
  2.   
  3. // 定义单链表的节点结构  
  4. struct ListNode {  
  5.     int val;  
  6.     ListNode* next;  
  7.     ListNode(int x) : val(x), next(NULL) {}  
  8. };  
  9.   
  10. // 复制单链表的函数  
  11. ListNode* copyLinkedList(ListNode* head) {  
  12.     if (head == NULL) {  
  13.         return NULL; // 如果原链表为空,返回空指针  
  14.     }  
  15.   
  16.     // 创建一个新链表的头节点,并初始化当前节点指针  
  17.     ListNode* newHead = new ListNode(head->val);  
  18.     ListNode* currentNew = newHead;  
  19.     ListNode* currentOld = head->next;  
  20.   
  21.     // 遍历原链表,复制节点  
  22.     while (currentOld != NULL) {  
  23.         // 复制节点值  
  24.         currentNew->next = new ListNode(currentOld->val);  
  25.         currentNew = currentNew->next;  
  26.         currentOld = currentOld->next;  
  27.     }  
  28.   
  29.     return newHead;  
  30. }  
  31.   
  32. int main() {  
  33.     // 创建一个单链表:1 -> 2 -> 3 -> 4  
  34.     ListNode* head = new ListNode(1);  
  35.     head->next = new ListNode(2);  
  36.     head->next->next = new ListNode(3);  
  37.     head->next->next->next = new ListNode(4);  
  38.   
  39.     // 调用复制链表的函数  
  40.     ListNode* newHead = copyLinkedList(head);  
  41.   
  42.     // 输出新链表的节点值  
  43.     ListNode* current = newHead;  
  44.     while (current != NULL) {  
  45.         std::cout << current->val << " ";  
  46.         current = current->next;  
  47.     }  
  48.     std::cout << std::endl;  
  49.   
  50.     // 释放内存  
  51.     delete head->next->next->next;  
  52.     delete head->next->next;  
  53.     delete head->next;  
  54.     delete head;  
  55.   
  56.     // 释放新链表内存  
  57.     current = newHead;  
  58.     while (current != NULL) {  
  59.         ListNode* temp = current;  
  60.         current = current->next;  
  61.         delete temp;  
  62.     }  
  63.   
  64.     return 0;  
  65. }  

c++已知一个无序单链表,表中结点的data字段为正整数,编写算法按递增顺序打印表中结点的值,写出完整程序和示例,注意内存管理

这个程序首先定义了一个单链表的结构体 ListNode,然后实现了三个函数:

  1. insertSorted:将一个新节点按递增顺序插入到已排序链表中。
  2. printSorted:按递增顺序打印链表节点的值。
  3. deleteList:释放链表内存。

main 函数中,我们创建了一个无序单链表,然后创建了一个新的已排序链表的头节点。接着,遍历无序链表,将节点插入已排序链表。最后,打印已排序链表的节点值,并释放内存以避免内存泄漏。

  1. #include <iostream>  
  2.   
  3. // 定义单链表的节点结构  
  4. struct ListNode {  
  5.     int data;  
  6.     ListNode* next;  
  7.     ListNode(int x) : data(x), next(NULL) {}  
  8. };  
  9.   
  10. // 插入新节点到已排序链表中  
  11. void insertSorted(ListNode*& sortedHead, ListNode* newNode) {  
  12.     if (sortedHead == NULL || sortedHead->data >= newNode->data) {//更新头结点  
  13.         newNode->next = sortedHead;  
  14.         sortedHead = newNode;  
  15.     }  
  16.     else {  
  17.         ListNode* current = sortedHead;  
  18.         while (current->next != NULL && current->next->data < newNode->data) {  
  19.             current = current->next;  
  20.         }  
  21.         newNode->next = current->next;  
  22.         current->next = newNode;  
  23.     }  
  24. }  
  25.   
  26. // 按递增顺序打印链表节点的值  
  27. void printSorted(ListNode* head) {  
  28.     while (head != NULL) {  
  29.         std::cout << head->data << " ";  
  30.         head = head->next;  
  31.     }  
  32.     std::cout << std::endl;  
  33. }  
  34.   
  35. // 释放链表内存  
  36. void deleteList(ListNode* head) {  
  37.     while (head != NULL) {  
  38.         ListNode* temp = head;  
  39.         head = head->next;  
  40.         delete temp;  
  41.     }  
  42. }  
  43.   
  44. int main() {  
  45.     // 创建一个无序单链表:3 -> 1 -> 4 -> 2  
  46.     ListNode* head = new ListNode(3);  
  47.     head->next = new ListNode(1);  
  48.     head->next->next = new ListNode(4);  
  49.     head->next->next->next = new ListNode(2);  
  50.   
  51.     // 创建一个新的已排序链表的头节点  
  52.     ListNode* sortedHead = NULL;  
  53.   
  54.     // 遍历无序链表,并将节点插入已排序链表  
  55.     ListNode* current = head;  
  56.     while (current != NULL) {  
  57.         ListNode* newNode = new ListNode(current->data);  
  58.         insertSorted(sortedHead, newNode);  
  59.         current = current->next;  
  60.     }  
  61.   
  62.     // 打印已排序链表的节点值  
  63.     printSorted(sortedHead);  
  64.   
  65.     // 释放内存  
  66.     deleteList(head);  
  67.     deleteList(sortedHead);  
  68.   
  69.     return 0; 
  70. }

栈和队列

栈是只能在一端进行插入或删除的线性表

允许插入,删除的一端称为栈顶,另一端称为栈底

栈中没有元素时称为空栈

顺序栈的操作

  1. #include<iostream>  
  2. #include<vector>  
  3. using namespace std;  
  4. class stack  
  5. {  
  6.     //栈顶是vectorback元素  
  7. private:  
  8.     vector<int>data;  
  9. public:  
  10.     //初始化栈  
  11.     stack() {}  
  12.   
  13.     //入栈操作  
  14.     void push(int val)  
  15.     {  
  16.         data.push_back(val);  
  17.     }  
  18.   
  19.     //出栈操作  
  20.     void pop()  
  21.     {  
  22.         if (!isempty()) data.pop_back();  
  23.         else cout << "已经空了" << endl;  
  24.     }  
  25.   
  26.     //取栈顶元素  
  27.     int top()const  
  28.     {  
  29.         if (!isempty()) return data.back();  
  30.         else  
  31.         {  
  32.             cout << "栈空" << endl;  
  33.             return -1;  
  34.         }  
  35.     }  
  36.   
  37.     //判断栈是否为空  
  38.     bool isempty() const  
  39.     {  
  40.         return data.empty();  
  41.     }  
  42.   
  43.  };  
  44.   
  45. int main()  
  46. {  
  47.     stack s;  
  48.     s.push(1);  
  49.     s.push(2);  
  50.     s.push(3);  
  51.   
  52.     cout << "栈顶元素" << s.top() << endl;  
  53.     s.pop();  
  54.     cout << "栈顶元素" << s.top() << endl;  
  55.   
  56.     while (!s.isempty()) s.pop();  
  57.     cout << "栈顶元素" << s.top() << endl;  
  58.   
  59.     return 0;  
  60. }  

链栈的操作

  1. #include<iostream>  
  2. #include<list>  
  3. using namespace std;  
  4.   
  5. //个人感觉就是把链表竖起来放  
  6.   
  7. class linkstcak  
  8. {  
  9. private:  
  10.     //定义链栈结点  
  11.     struct node  
  12.     {  
  13.         int data;  
  14.         node* next;  
  15.         node(int val):data(val),next(nullptr){}  
  16.     };  
  17.     node* topnode;//栈顶指针  
  18.   
  19. public:  
  20.       
  21.     //判断栈是否为空  
  22.     bool isempty() const  
  23.     {  
  24.         return topnode == nullptr;  
  25.     }  
  26.   
  27.   
  28.     //初始化链栈  
  29.     linkstcak():topnode(nullptr){}  
  30.   
  31.     //入栈操作  
  32.     void push(int val)  
  33.     {  
  34.         node* newn = new node(val);  
  35.         newn->next = topnode;  
  36.         topnode = newn;  
  37.     }  
  38.   
  39.     //出栈操作  
  40.     void pop()  
  41.     {  
  42.         if (!isempty())  
  43.         {  
  44.             node* tem = topnode;  
  45.             topnode = topnode->next;  
  46.             delete tem;  
  47.         }  
  48.         else cout << "栈空" << endl;  
  49.     }  
  50.   
  51.     //取栈顶元素  
  52.     int top() const  
  53.     {  
  54.         if (!isempty()) return topnode->data;  
  55.         else  
  56.         {  
  57.             cout << "栈空" << endl;  
  58.             return -1;  
  59.         }  
  60.     }  
  61.   
  62.     //析构  
  63.     ~linkstcak()  
  64.     {  
  65.         while (topnode != nullptr)  
  66.         {  
  67.             node* tem = topnode;  
  68.             topnode = topnode->next;  
  69.             delete tem;  
  70.         }  
  71.     }  
  72.   
  73. };  
  74.   
  75. int main()  
  76. {  
  77.     linkstcak s;  
  78.     s.push(1);  
  79.     s.push(2);  
  80.     s.push(3);  
  81.     cout << s.top() << endl;  
  82.   
  83.     s.pop();  
  84.     cout << s.top() << endl;  
  85.   
  86.     return 0;  
  87. }  

栈的应用:

算符优先法求算数表达式的值

  1. #include<iostream>  
  2. #include<stack>  
  3. #include<unordered_map>  
  4. #include<cctype>//isspace(ch), isdigit(ch)  
  5. #include<string>  
  6. using namespace std;  
  7.   
  8. //定义运算符优先级  
  9. unordered_map<char,int> prece= { {'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}, {'^', 3} };  
  10.   
  11. //判断字符是否为运算符  
  12. bool isop(char ch)  
  13. {  
  14.     return prece.find(ch) != prece.end();  
  15. }  
  16.   
  17. //比较运算符优先级  
  18. int com(char op1, char op2)  
  19. {  
  20.     return prece[op1] - prece[op2];  
  21. }  
  22.   
  23. //计算二元运算  
  24. int ap(int a, char op, int b)  
  25. {  
  26.     switch (op)  
  27.     {  
  28.     case '+'return a + b;  
  29.     case '-'return a - b;  
  30.     case '*'return a * b;  
  31.     case '/'return a / b;  
  32.     case'^':return static_cast<int>(pow(a, b));  
  33.     //通过 static_cast<int> 将其转换为 int 类型,即取 double 类型的结果的整数部分。  
  34.     default:return 0;  
  35.     }  
  36. }  
  37.   
  38. //计算算数表达式的值  
  39. int eva(const string& ex)  
  40. {  
  41.     stack<int>rands;//操作数  
  42.     stack<char>ops;//运算符  
  43.   
  44.     for (char ch : ex)  
  45.     {  
  46.         if (isspace(ch)) continue;  
  47.         else if (isdigit(ch)) rands.push(ch - '0');// 处理数字  
  48.         else if (isop(ch)) // 处理运算符  
  49.         {  
  50.             while (!ops.empty() && com(ops.top(), ch) >= 0)  
  51.             {//如果运算符栈不为空且当前运算符的优先级小于等于栈顶运算符的优先级,  
  52.                 //执行计算,将结果推入 operands 栈,直到满足条件  
  53.                 int b = rands.top(); rands.pop();  
  54.                 int a = rands.top(); rands.pop();  
  55.                 char op = ops.top(); ops.pop();  
  56.                 rands.push(ap(a, op, b));  
  57.             }  
  58.             ops.push(ch);//将当前运算符推入 operators 栈。  
  59.         }  
  60.         else if (ch == '(')  ops.push(ch);//左括号入栈  
  61.         else if (ch == ')')  
  62.         {  
  63.             while (!ops.empty() && ops.top() != '(')  
  64.             {//如果字符是闭括号 ')',执行计算,直到遇到与之匹配的开括号 '('  
  65.                 //并将结果推入 operands   
  66.                 int b = rands.top(); rands.pop();  
  67.                 int a = rands.top(); rands.pop();  
  68.                 char op = ops.top(); ops.pop();  
  69.                 rands.push(ap(a, op, b));  
  70.             }  
  71.             ops.pop();//弹出左括号  
  72.         }  
  73.     }  
  74.     //处理剩余运算符 可能是嵌套的括号之类的  
  75.     while (!ops.empty())  
  76.     {  
  77.         int b = rands.top(); rands.pop();  
  78.         int a = rands.top(); rands.pop();  
  79.         char op = ops.top(); ops.pop();  
  80.         rands.push(ap(a, op, b));  
  81.     }  
  82.     //返回最终结果  
  83.     return rands.top();  
  84. }  
  85. int main()  
  86. {  
  87.     string ex;  
  88.     getline(cin, ex);  
  89.     int re = eva(ex);  
  90.     cout << re << endl;  
  91.     return 0;  
  92. }  

递归的含义:函数直接调用自己或者通过一系列调用语句间接调用自己

递归的条件:

大问题可以分解为小问题

可以确定递归到何时为止

求阶乘的递归算法

int fact(int n)

{

    if (n == 0) return 1;

    else return n * fact(n - 1);

}

编号为1 2 3 4 5的5辆列车顺序开进一个栈式结构的站点,问开出车站的顺序有多少种可能,请具体写出所有可能的出栈序列

可以使用递归的方法来解决

  1. #include <iostream>  
  2. #include <vector>  
  3.   
  4. void generatePermutations(vector<int> inStack,  vector<int> outStack, vector<int> result) {  
  5.     // 如果输入栈和输出栈都为空,表示一种可能的出栈顺序  
  6.     if (inStack.empty() && outStack.empty()) {  
  7.         for (int num : result)      cout << num << " ";  
  8.         cout <<  endl;  
  9.         return;  
  10.     }  
  11.   
  12.     // 尝试将一个车厢从输入栈移到输出栈  
  13.     if (!inStack.empty()) {  
  14.         std::vector<int> newInStack = inStack;  
  15.         std::vector<int> newOutStack = outStack;  
  16.         std::vector<int> newResult = result;  
  17.   
  18.         newOutStack.push_back(newInStack.back());  
  19.         newInStack.pop_back();  
  20.   
  21.         generatePermutations(newInStack, newOutStack, newResult);  
  22.     }  
  23.   
  24.     // 尝试将一个车厢从输出栈中出栈  
  25.     if (!outStack.empty()) {  
  26.         std::vector<int> newInStack = inStack;  
  27.         std::vector<int> newOutStack = outStack;  
  28.         std::vector<int> newResult = result;  
  29.   
  30.         newResult.push_back(newOutStack.back());  //在容器的尾部添加一个元素的函数
  31.         newOutStack.pop_back();  //删除容器的尾部元素的函数
  32.   
  33.         generatePermutations(newInStack, newOutStack, newResult);  
  34.     }  
  35. }  
  36.   
  37. int main() {  
  38.     std::vector<int> inStack = {1, 2, 3, 4, 5};  
  39.     std::vector<int> outStack;  
  40.     std::vector<int> result;  
  41.   
  42.     generatePermutations(inStack, outStack, result);  
  43.   
  44.     return 0;  
  45. }  

利用栈实现把十进制整数转换为二进制至十六进制之间的任一进制数并输出的功能

  1. #include <iostream>  
  2. #include <stack>  
  3. #include <string>  
  4.   
  5. // 将十进制数转换为其他进制  
  6. std::string decimalToBase(int num, int base) {  
  7.     std::stack<char> result;  
  8.   
  9.     while (num > 0) {  
  10.         int remainder = num % base;  
  11.         char digit;  
  12.         if (remainder < 10) {  
  13.             digit = '0' + remainder;  
  14.         } else {  
  15.             digit = 'A' + remainder - 10;  
  16.         }  
  17.         result.push(digit);  
  18.         num /= base;  
  19.     }  
  20.   
  21.     std::string converted;  
  22.     while (!result.empty()) {  
  23.         converted += result.top();  
  24.         result.pop();  
  25.     }  
  26.   
  27.     return converted;  
  28. }  
  29.   
  30. int main() {  
  31.     int decimalNumber;  
  32.     std::cout << "输入一个十进制整数: ";  
  33.     std::cin >> decimalNumber;  
  34.   
  35.     std::string binary = decimalToBase(decimalNumber, 2);  
  36.     std::string octal = decimalToBase(decimalNumber, 8);  
  37.     std::string hexadecimal = decimalToBase(decimalNumber, 16);  
  38.   
  39.     std::cout << "二进制表示: " << binary << std::endl;  
  40.     std::cout << "八进制表示: " << octal << std::endl;  
  41.     std::cout << "十六进制表示: " << hexadecimal << std::endl;  
  42.   
  43.     return 0;  
  44. }  

设有一维数组stack[],将其分配给两个栈s1和s2使用,试问如何分配数组空间,使得对任何一个栈,当且仅当数组空间全满时才不能插入,分别给出两个栈的出栈入栈算法

要将一个一维数组 `stack` 分配给两个栈 `s1` 和 `s2`,并使得只有当数组空间全满时才不能插入,可以采取以下策略:

1. 将数组的两端作为两个栈的起始点,分别向中间延伸。假设数组长度为 `n`,则 `s1` 从数组的左端开始, `s2` 从数组的右端开始,它们向中间延伸。

2. 为了使得两个栈的空间都能够被充分利用,可以让它们分别从两端向中间延伸,直到它们的栈顶指针相遇为止。

3. 当两个栈的栈顶指针相遇时,表示数组空间已经被完全利用,此时再进行插入操作会导致栈溢出。

以下是两个栈的基本操作:

**栈s1:**

- `s1_top`: 指向栈 `s1` 的栈顶元素位置。

- `s1_push(x)`: 将元素 `x` 压入栈 `s1`,操作前需判断 `s1_top` 是否等于 `s2_top`,若相等则栈满。

- `s1_pop()`: 弹出栈 `s1` 的栈顶元素,操作前需判断 `s1_top` 是否等于 `-1`,若等于 `-1` 则栈空。

**栈s2:**

- `s2_top`: 指向栈 `s2` 的栈顶元素位置。

- `s2_push(x)`: 将元素 `x` 压入栈 `s2`,操作前需判断 `s2_top` 是否等于 `s1_top`,若相等则栈满。

- `s2_pop()`: 弹出栈 `s2` 的栈顶元素,操作前需判断 `s2_top` 是否等于 `n`,若等于 `n` 则栈空。

具体实现可以采用相应的数据结构(比如数组)以及相应的指针来管理两个栈的操作。需要注意的是,在进行任何操作前,都需要进行相应的栈满或栈空检查,以保证程序的健壮性。

  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. const int MAX_SIZE = 100;  // 假设数组大小为100  
  5.   
  6. class TwoStacks {  
  7. private:  
  8.     int stack[MAX_SIZE];  
  9.     int s1_top;  // 1的栈顶指针  
  10.     int s2_top;  // 2的栈顶指针  
  11.   
  12. public:  
  13.     TwoStacks() {  
  14.         s1_top = -1;  // 初始化栈1的栈顶指针  
  15.         s2_top = MAX_SIZE;  // 初始化栈2的栈顶指针  
  16.     }  
  17.   
  18.     void s1_push(int x) {  
  19.         if (s1_top + 1 == s2_top) {  
  20.             cout << "栈满,无法插入" << endl;  
  21.             return;  
  22.         }  
  23.         stack[++s1_top] = x;  
  24.     }  
  25.   
  26.     void s2_push(int x) {  
  27.         if (s2_top - 1 == s1_top) {  
  28.             cout << "栈满,无法插入" << endl;  
  29.             return;  
  30.         }  
  31.         stack[--s2_top] = x;  
  32.     }  
  33.   
  34.     int s1_pop() {  
  35.         if (s1_top == -1) {  
  36.             cout << "1为空" << endl;  
  37.             return -1;  // 返回一个特定值表示栈为空  
  38.         }  
  39.         return stack[s1_top--];  
  40.     }  
  41.   
  42.     int s2_pop() {  
  43.         if (s2_top == MAX_SIZE) {  
  44.             cout << "2为空" << endl;  
  45.             return -1;  // 返回一个特定值表示栈为空  
  46.         }  
  47.         return stack[s2_top++];  
  48.     }  
  49. };  
  50.   
  51. int main() {  
  52.     TwoStacks ts;  
  53.     ts.s1_push(1);  
  54.     ts.s1_push(2);  
  55.     ts.s2_push(3);  
  56.     ts.s2_push(4);  
  57.   
  58.     cout << "s1出栈结果:" << ts.s1_pop() << endl;  
  59.     cout << "s2出栈结果:" << ts.s2_pop() << endl;  
  60.   
  61.     return 0;  
  62. }  

假设表达式中允许包含3种括号:圆括号,方括号和大括号,试编写一个算法,检查表达式中括号是否配对,能全部配对返回1,否则返回0

  1. #include <iostream>  
  2. #include <stack>  
  3. #include <string>  
  4.   
  5. int checkBracketPairing(const std::string& expression) {  
  6.     std::stack<char> brackets;  
  7.   
  8.     for (char c : expression) {  
  9.         if (c == '(' || c == '[' || c == '{') {  
  10.             brackets.push(c);  
  11.         } else if (c == ')' || c == ']' || c == '}') {  
  12.             if (brackets.empty()) {  
  13.                 return 0; // 遇到右括号但栈为空,不配对  
  14.             }  
  15.             char top = brackets.top();  
  16.             brackets.pop();  
  17.             if ((c == ')' && top != '(') ||  
  18.                 (c == ']' && top != '[') ||  
  19.                 (c == '}' && top != '{')) {  
  20.                 return 0; // 括号不匹配  
  21.             }  
  22.         }  
  23.     }  
  24.   
  25.     return brackets.empty() ? 1 : 0;  
  26. }  
  27.   
  28. int main() {  
  29.     std::string expression1 = "{[()]}";  
  30.     std::string expression2 = "{[(])}";  
  31.   
  32.     int result1 = checkBracketPairing(expression1);  
  33.     int result2 = checkBracketPairing(expression2);  
  34.   
  35.     std::cout << "Result for expression1: " << result1 << std::endl;  
  36.     std::cout << "Result for expression2: " << result2 << std::endl;  
  37.   
  38.     return 0;  
  39. }  

队列

队列是一种在一段进行插入,在另一端进行删除的线性表

允许插入的叫队尾

允许删除的叫队头

循环队列的操作

  1. #include<iostream>  
  2. using namespace std;  
  3. const int MAX = 5;//定义循环队列的最大容量  
  4.   
  5. class ccq  
  6. {  
  7. private:  
  8.     int front;//队头  
  9.     int rear;//队尾  
  10.     int arr[MAX];  
  11.       
  12. public:  
  13.     ccq():front(-1),rear(-1){}//初始化循环队列  
  14.   
  15.     //判断队列是否为空  
  16.     bool isempty()  
  17.     {  
  18.         return front == -1 && rear == -1;  
  19.     }  
  20.   
  21.     //判读队列是否为满 ************************  
  22.     bool isfull()  
  23.     {  
  24.         return (rear + 1) % MAX == front;  
  25.     }  
  26.   
  27.     //入队  
  28.     void en(int e)  
  29.     {  
  30.         if (isfull())  
  31.         {  
  32.             cout << "满了" << endl;  
  33.             return;  
  34.         }  
  35.         if (isempty())  
  36.             front = rear = 0;//第一个元素入队  
  37.         else  
  38.             rear = (rear + 1) % MAX;//队尾后移  

arr[rear] = e;//将元素放入队尾

  1.     }  
  2.   
  3.     //出队  
  4.     void de()  
  5.     {  
  6.         if (isempty())  
  7.         {  
  8.             cout << "空的" << endl;  
  9.             return;  
  10.         }  
  11.         if (front == rear) front = rear = -1;//队列中只有一个元素,出队后队列变为空  
  12.         else front = (front + 1) % MAX;//队头后移  
  13.     }  
  14. };  
  15.   
  16. int main()  
  17. {  
  18.     return 0;  
  19. }  

若循环队列以数组Q【0····m-1】作为其存储结构,变量rear表示循环队列中队尾元素的实际位置,其移动按rear=(rear+1)mod m进行,变量length表示当前循环队列的元素的个数,则循环队列的对首元素的实际位置是

(1+rear+m-length)mod m其中加一是因为需要从队尾的后一个元素算起,不加一的话就会使队尾数据也纳入空队列的计算中

链队列的操作

  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. struct node  
  5. {  
  6.     int data;  
  7.     node* next;  
  8.     node(int val) :data(val), next(nullptr) {}  
  9. };  
  10.   
  11. class lq  
  12. {  
  13. private:  
  14.     node* front;//队头指针  
  15.     node* rear;//队尾指针  
  16.   
  17. public:  
  18.     //初始化链队列  
  19.     lq() :front(nullptr), rear(nullptr) {}  
  20.   
  21.     //判断链队是否为空  
  22.     bool isempty()  
  23.     {  
  24.         return front == nullptr;  
  25.     }  
  26.   
  27.     //入队操作  
  28.     void en(int e)  
  29.     {  
  30.         node* newn = new node(e);  
  31.         if (isempty()) front = rear = newn;//队列为空,新节点成为队头和队尾  
  32.         else  
  33.         {//新节点放入队尾,更新队尾指针  
  34.             rear->next = newn;  
  35.             rear = newn;  
  36.         }  
  37.     }  
  38.   
  39.     void de()  
  40.     {  
  41.         if (isempty())  
  42.         {  
  43.             cout << "空的" << endl;  
  44.             return;  
  45.         }  
  46.         node* tem = front;  
  47.         if (front == rear) front = rear = nullptr;//只有一个节点 删了后为空队列  
  48.         else front = front->next;  
  49.         delete tem;  
  50.     }  
  51. };  

队列的应用:

队列求解报数问题

  1. #include<iostream>  
  2. #include<queue>  
  3. using namespace std;  
  4.   
  5. void jo(int n, int m)  
  6. {  
  7.     queue<int>q;  
  8.     // 初始化队列,将所有人编号入队  
  9.     for (int i = 1; i <= n; i++) q.push(i);  
  10.     // 开始报数  
  11.     while (!q.empty())  
  12.     {  
  13.         // 报数到m的人出列  
  14.         for (int i = 1; i <= m; i++)  
  15.         {  
  16.             int front = q.front();  
  17.             q.pop();  
  18.             q.push(front);  
  19.         }  
  20.         cout << q.front()<<" ";  
  21.         q.pop();  
  22.     }  
  23. }  
  24.   
  25. int main()  
  26. {  
  27.     int n, m;  
  28.     cin >> n >> m;  
  29.     jo(n, m);  
  30.   
  31.     return 0;  
  32.   
  33. }  

约瑟夫问题

假设以一维数组data[m]储存循环队列的元素,若要使这m个分量都得到应用,则另设一辅助标志变量flag判断队列的状态为空还是满,试编写入队和出队算法

  1. const int MAX_SIZE = 100; // 假设队列的最大容量为100  
  2.   
  3. class CircularQueue {  
  4. private:  
  5.     int data[MAX_SIZE];  
  6.     int front; // 队头指针  
  7.     int rear;  // 队尾指针  
  8.     int flag;  // 队列状态标志,0表示空,1表示满  
  9.   
  10. public:  
  11.     CircularQueue() {  
  12.         front = rear = 0;  
  13.         flag = 0; // 初始状态为队列空  
  14.     }  
  15.   
  16.     bool isEmpty() {  
  17.         return flag == 0;  
  18.     }  
  19.   
  20.     bool isFull() {  
  21.         return flag == 1;  
  22.     }  
  23.   
  24.     void enqueue(int x) {  
  25.         if (isFull()) {  
  26.             std::cout << "队列已满,无法入队" << std::endl;  
  27.             return;  
  28.         }  
  29.   
  30.         data[rear] = x;  
  31.         rear = (rear + 1) % MAX_SIZE;  
  32.         if (rear == front) {  
  33.             flag = 1; // 队列满  
  34.         }  
  35.     }  
  36.   
  37.     int dequeue() {  
  38.         if (isEmpty()) {  
  39.             std::cout << "队列为空,无法出队" << std::endl;  
  40.             return -1; // 返回一个特定值表示队列为空  
  41.         }  
  42.   
  43.         int value = data[front];  
  44.         front = (front + 1) % MAX_SIZE;  
  45.         flag = 0; // 出队后队列状态为非满  
  46.   
  47.         return value;  
  48.     }  
  49. };  

假设以带头结点的循环链表表示队列,并且只设一个表尾指针,试编写相应的置队列空,入队和出队操作

  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. // 链表结点定义  
  5. struct ListNode {  
  6.     int val;  
  7.     ListNode* next;  
  8.     ListNode(int x) : val(x), next(NULL) {}  
  9. };  
  10.   
  11. class CircularQueue {  
  12. private:  
  13.     ListNode* rear;  // 队尾指针,指向链表的最后一个节点  
  14. public:  
  15.     // 构造函数  
  16.     CircularQueue() {  
  17.         rear = NULL;  
  18.     }  
  19.   
  20.     // 置队列空  
  21.     void makeEmpty() {  
  22.         if (rear == NULL) return;  // 队列已空  
  23.         ListNode* temp = rear->next;  // 头结点  
  24.         rear->next = NULL;  // 尾节点指向空  
  25.         while (temp != NULL) {  
  26.             ListNode* nextNode = temp->next;  
  27.             delete temp;  
  28.             temp = nextNode;  
  29.         }  
  30.         rear = NULL;  // 重置rear  
  31.     }  
  32.   
  33.     // 入队  
  34.     void enqueue(int x) {  
  35.         ListNode* newNode = new ListNode(x);  
  36.         if (rear == NULL) {  
  37.             rear = newNode;  
  38.             rear->next = rear;  // 链接到自身形成环  
  39.         } else {  
  40.             newNode->next = rear->next;  
  41.             rear->next = newNode;  
  42.             rear = newNode;  
  43.         }  
  44.     }  
  45.   
  46.     // 出队  
  47.     int dequeue() {  
  48.         if (rear == NULL) {  
  49.             cout << "队列为空,无法出队" << endl;  
  50.             return -1;  // 返回一个特定值表示队列为空  
  51.         }  
  52.         ListNode* front = rear->next;  
  53.         int value = front->val;  
  54.         if (front == rear) {  
  55.             rear = NULL;  // 队列中只有一个节点,出队后置空rear  
  56.         } else {  
  57.             rear->next = front->next;  
  58.         }  
  59.         delete front;  
  60.         return value;  
  61.     }  
  62. };  
  63.   
  64. int main() {  
  65.     CircularQueue queue;  
  66.     queue.enqueue(1);  
  67.     queue.enqueue(2);  
  68.     queue.enqueue(3);  
  69.   
  70.     while (true) {  
  71.         int value = queue.dequeue();  
  72.         if (value == -1) break;  // 队列为空时跳出循环  
  73.         cout << "出队元素: " << value << endl;  
  74.     }  
  75.   
  76.     return 0;  
  77. }

如何用两个栈实现队列,写出队列基本操作的算法

使用两个栈可以实现队列的基本操作。一个栈用于入队操作,另一个栈用于出队操作。具体步骤如下:

1. **入队操作**:

   - 将元素压入第一个栈(称为 `stack1`)中。

2. **出队操作**:

   - 如果第二个栈(称为 `stack2`)不为空,直接从 `stack2` 弹出栈顶元素。

   - 如果 `stack2` 为空,将 `stack1` 中的所有元素依次弹出并压入 `stack2`,然后从 `stack2` 弹出栈顶元素。

下面是基于C++的实现:

```cpp

#include <iostream>

#include <stack>

using namespace std;

class MyQueue {

private:

    stack<int> stack1;  // 用于入队

    stack<int> stack2;  // 用于出队

    void moveElements() {

        while (!stack1.empty()) {

            stack2.push(stack1.top());

            stack1.pop();

        }

    }

public:

    void enqueue(int x) {

        stack1.push(x);

    }

    int dequeue() {

        if (stack2.empty()) {

            moveElements();

        }

        if (!stack2.empty()) {

            int front = stack2.top();

            stack2.pop();

            return front;

        } else {

            cout << "队列为空" << endl;

            return -1;  // 返回一个特定值表示队列为空

        }

    }

};

int main() {

    MyQueue queue;

    queue.enqueue(1);

    queue.enqueue(2);

    queue.enqueue(3);

    cout << "出队元素: " << queue.dequeue() << endl;

    cout << "出队元素: " << queue.dequeue() << endl;

    cout << "出队元素: " << queue.dequeue() << endl;

    cout << "出队元素: " << queue.dequeue() << endl; // 队列为空

    return 0;

}

```

在这段代码中,我们定义了一个 `MyQueue` 类,其中包括了入队和出队操作。具体实现如下:

- `enqueue` 将元素压入 `stack1` 中。

- `dequeue` 首先检查 `stack2` 是否为空,如果不为空则直接从 `stack2` 中弹出栈顶元素。如果 `stack2` 为空,调用 `moveElements` 函数将 `stack1` 中的元素移动到 `stack2` 中,然后再从 `stack2` 弹出栈顶元素。

在 `main` 函数中,我们创建了一个 `MyQueue` 对象 `queue`,并进行了入队和出队操作。出队操作会依次输出出队的元素。当队列为空时,会输出相应的提示信息。

  1. #include <iostream>  
  2. #include <stack>  
  3. using namespace std;  
  4.   
  5. class MyQueue {  
  6. private:  
  7.     stack<int> stack1;  // 用于入队  
  8.     stack<int> stack2;  // 用于出队  
  9.   
  10.     void moveElements() {  
  11.         while (!stack1.empty()) {  
  12.             stack2.push(stack1.top());  
  13.             stack1.pop();  
  14.         }  
  15.     }  
  16.   
  17. public:  
  18.     void enqueue(int x) {  
  19.         stack1.push(x);  
  20.     }  
  21.   
  22.     int dequeue() {  
  23.         if (stack2.empty()) {  
  24.             moveElements();  
  25.         }  
  26.   
  27.         if (!stack2.empty()) {  
  28.             int front = stack2.top();  
  29.             stack2.pop();  
  30.             return front;  
  31.         } else {  
  32.             cout << "队列为空" << endl;  
  33.             return -1;  // 返回一个特定值表示队列为空  
  34.         }  
  35.     }  
  36. };  
  37.   
  38. int main() {  
  39.     MyQueue queue;  
  40.     queue.enqueue(1);  
  41.     queue.enqueue(2);  
  42.     queue.enqueue(3);  
  43.   
  44.     cout << "出队元素: " << queue.dequeue() << endl;  
  45.     cout << "出队元素: " << queue.dequeue() << endl;  
  46.     cout << "出队元素: " << queue.dequeue() << endl;  
  47.     cout << "出队元素: " << queue.dequeue() << endl; // 队列为空  
  48.   
  49.     return 0;  
  50. }  
  • 20
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值