使用兩個棧實現佇列的 C++ 程式


棧是一種後進先出 (LIFO) 的資料結構,其中插入和刪除操作都在同一端(頂部)進行。最後進入的元素首先被刪除。

棧的操作包括:

  • push (int data) − 在頂部插入元素
  • int pop() − 從頂部刪除元素

佇列

佇列是一種先進先出 (FIFO) 的資料結構,其中插入操作在隊尾進行,刪除操作在隊首進行。第一個進入的元素首先被刪除。

佇列的操作包括:

  • EnQueue (int data) − 在隊尾插入元素
  • int DeQueue() − 從隊首刪除元素

這是一個使用兩個棧實現佇列的 C++ 程式。

函式描述

  • enQueue() 函式用於將元素入隊
    • 將 m 推入 s1。
  • deQueue() 函式用於將元素出隊。
    • 如果兩個棧都為空,則列印佇列為空。
    • 如果 s2 為空,則將 s1 中的元素移動到 s2。
    • 從 s2 中彈出元素並返回。
  • push() 函式用於將元素壓入棧。
  • pop() 函式用於從棧中彈出元素。

示例程式碼

#include<stdlib.h>
#include<iostream>
using namespace std;

struct nod//node declaration {
   int d;
   struct nod *n;
};

void push(struct nod** top_ref, int n_d);//functions prototypes.
int pop(struct nod** top_ref);

struct queue {
   struct nod *s1;
   struct nod *s2;
};

void enQueue(struct queue *q, int m) {
   push(&q->s1, m);
}

int deQueue(struct queue *q) {
   int m;
   if (q->s1 == NULL && q->s2 == NULL) {
      cout << "Queue is empty";
      exit(0);
   }
   if (q->s2 == NULL) {
      while (q->s1 != NULL) {
         m = pop(&q->s1);
         push(&q->s2, m);
      }
   }
   m = pop(&q->s2);
   return m;
}

void push(struct nod** top_ref, int n_d) {
   struct nod* new_node = (struct nod*) malloc(sizeof(struct nod));

   if (new_node == NULL) {
      cout << "Stack underflow \n";
      exit(0);
   }
   //put items on stack
   new_node->d= n_d;
   new_node->n= (*top_ref);
   (*top_ref) = new_node;
}

int pop(struct nod** top_ref) {
   int res;
   struct nod *top;
   if (*top_ref == NULL)//if stack is null {
      cout << "Stack overflow \n";
      exit(0);
   } else { //pop elements from stack
      top = *top_ref;
      res = top->d;
      *top_ref = top->n;
      free(top);
      return res;
   }
}

int main() {
   struct queue *q = (struct queue*) malloc(sizeof(struct queue));
   q->s1 = NULL;
   q->s2 = NULL;
   cout << "Enqueuing..7";
   cout << endl;
   enQueue(q, 7);
   cout << "Enqueuing..6";
   cout << endl;
   enQueue(q, 6);
   cout << "Enqueuing..2";
   cout << endl;
   enQueue(q, 2);
   cout << "Enqueuing..3";
   cout << endl;
   enQueue(q, 3);

   cout << "Dequeuing...";
   cout << deQueue(q) << " ";
   cout << endl;
   cout << "Dequeuing...";
   cout << deQueue(q) << " ";
   cout << endl;
   cout << "Dequeuing...";
   cout << deQueue(q) << " ";
   cout << endl;
}

輸出

Enqueuing..7
Enqueuing..6
Enqueuing..2
Enqueuing..3
Dequeuing...7
Dequeuing...6
Dequeuing...2

更新於: 2019-07-30

2K+ 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告