数据结构与算法——队列的实现(链表实现和两个栈实现)

曾经终败给现在 2022-02-28 05:34 272阅读 0赞

队列(queue)是限定只能在表的一端进行插入,在表的另一端进行删除的线性表。
允许插入的一端称为队尾(rear),允许删除的是队头(front)
在这里插入图片描述
//链表实现队列
//(1)添加的时候就添加链表的最后
//(2)弹出的时候就弹出头指针后一个位置的元素
//两个栈实现队列
//s2为空,先将s1全部装入s2再弹出

//链表实现队列

  1. #include <iostream>
  2. using namespace std;
  3. typedef struct Node
  4. {
  5. Node *next;
  6. int data;
  7. }Node;
  8. static Node *pHead = NULL;//头指针不包含数据
  9. Node * creat_node(int elem)
  10. {
  11. Node *p = (Node *)malloc(sizeof(Node));
  12. if (p == NULL)
  13. {
  14. return NULL;
  15. }
  16. p->next = NULL;
  17. p->data = elem;
  18. return p;
  19. }
  20. void push(int elem)
  21. {
  22. if (pHead == NULL)
  23. {
  24. return;
  25. }
  26. Node *p = creat_node(elem);
  27. //zy 找到尾部
  28. Node *q = pHead;
  29. while (q->next != NULL)
  30. {
  31. q = q->next;
  32. }
  33. q->next = p;
  34. p = NULL;
  35. q = NULL;
  36. }
  37. int front()
  38. {
  39. if (pHead->next == NULL)
  40. {
  41. return 0;
  42. }
  43. return pHead->next->data;
  44. }
  45. void pop()
  46. {
  47. if (pHead->next == NULL)
  48. {
  49. return;
  50. }
  51. Node *p = pHead->next;
  52. pHead->next = p->next;
  53. free(p);
  54. p = NULL;
  55. }
  56. int isEmpty()
  57. {
  58. if (pHead == NULL || pHead->next == NULL)
  59. {
  60. return true;
  61. }
  62. else
  63. {
  64. return false;
  65. }
  66. }
  67. int main()
  68. {
  69. //创建无数据的头结点
  70. pHead = (Node *)malloc(sizeof(Node));
  71. if (pHead == NULL)
  72. return NULL;
  73. pHead->next = NULL;
  74. push(10);
  75. push(20);
  76. push(30);
  77. pop();
  78. push(40);
  79. while (!isEmpty())
  80. {
  81. cout << front() << " ";
  82. pop();
  83. }
  84. cout << endl;
  85. return 0;
  86. }

//两个栈实现队列

  1. #include <iostream>
  2. #include <stack>
  3. using namespace std;
  4. stack<int> s1,s2;
  5. int length = 0;
  6. void push(int elem)
  7. {
  8. s1.push(elem);
  9. length ++;
  10. }
  11. int pop()
  12. {
  13. if(s2.empty()) //s2为空,先将s1全部装入s2再弹出
  14. {
  15. while (!s1.empty())
  16. {
  17. s2.push(s1.top());
  18. s1.pop();
  19. }
  20. }
  21. int temp = s2.top();
  22. s2.pop();
  23. --length;
  24. return temp;
  25. }
  26. int main()
  27. {
  28. push(10);
  29. push(20);
  30. push(30);
  31. pop(); pop();
  32. push(40);
  33. push(50);
  34. while (length)
  35. {
  36. cout << pop() << " ";
  37. }
  38. cout << endl;
  39. return 0;
  40. }

发表评论

表情:
评论列表 (有 0 条评论,272人围观)

还没有评论,来说两句吧...

相关阅读