队列
一种操作受限的线性表,只允许在表的一端进行插入,而在表的另一端进行删除.
队列的顺序存储结构
void InitQueue(SqQueue &s){
s.rear = s.front = 0;
}
bool IsEmpty(SqQueue s){
if(s.front == s.rear){
return true;
}
return false;
}
bool EnQueue(SqQueue &s, ElemType e){
if((s.rear + 1) % MaxSize == s.front)
return false;
s.data[s.rear] = e;
s.rear = (s.rear + 1) % MaxSize;
return true;
}
bool DeQueue(SqQueue &s, ElemType &e){
if(s.front == s.rear){
return false;
}
e = s.data[s.front];
s.front = (s.front + 1) % MaxSize;
return true;
}
队列的链式存储结构
#define ElemType char
typedef struct LinkNode
{
ElemType data;
LinkNode *next;
} LinkNode;
typedef struct LinkQueue
{
LinkNode *front;
LinkNode *rear;
};
void InitQueue(LinkQueue &Q){
Q.front = Q.rear = new LinkNode;
Q.rear->next = NULL;
}
bool IsEmpty(LinkQueue Q){
if(Q.rear == Q.front){
return true;
} else {
return false;
}
}
bool EnQueue(LinkQueue &Q, ElemType e){
LinkNode *tmp = new LinkNode;
tmp->data = e;
tmp->next = NULL;
Q.rear->next = tmp;
Q.rear = tmp;
}
bool DeQueue(LinkQueue &Q, ElemType &e){
if(Q.rear == Q.front) return false;
LinkNode *tmp = Q.front->next;
e = tmp->data;
Q.front->next = tmp->next;
if(tmp == Q.rear){
Q.rear = Q.front;
}
delete(tmp);
return true;
}
问题
问题一 : Q
是一个队列, S
是一个空栈, 实现将队列中的元素逆置.
#include <iostream>
#include <stdio.h>
#include <stack>
#include <queue>
using namespace std;
void Converse(queue<char> &q){
stack<char> s;
while(!q.empty()){
s.push(q.front());
q.pop();
}
while(!s.empty()){
q.push(s.top());
s.pop();
}
}
int main(){
queue<char> q;
int n;
while((n = getchar()) != EOF){
q.push(n);
}
Converse(q);
while(!q.empty()){
cout << q.front();
q.pop();
}
cout << endl;
}
问题二 :利用两个栈S1, S2来模拟一个队列, 实现队列的出队, 入队, 判空
三个操作.
/* 判空 */
int QueueEmpty(Stack S1, Stack S2){
if(StackEmpty(S1) && StackEmpty(S2)){
return 1;
} else {
return 0
}
}
/* 出队 */
void DeQueue(Stack &S1, Stack &S2, ElemType &e){
if(!StackEmpty(S2)){
Pop(S2, x);
} else if(StackEmpty(S1)){
printf("队列为空\n");
} else {
while(!StackEmpty(S1)){
Pop(S1, x);
Push(S2, x);
}
Pop(S2, x);
}
}
/* 入队 */
int EnQueue(Stack &S1, Stack &S2, ElemType e){
if(!StackOverflow(S1)){
Push(S1, e);
return 1;
}
if(StackOverflow(S1) && !StackEmpty(S2)){
printf("队列满\n");
return 0;
}
if(StackOverflow(S1) && StackEmpty(S2)){
while(!StackEmpty(S1)){
Pop(S1, x);
Push(S2, x);
}
}
Push(S1, e);
return 1;
}