使用两个栈实现队列的 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP