/*3)假设栈的输入序列为1、2、3、...、n,设计算法求出所有可能的出栈序列。
比如输入1、2、3、4、5,可能出栈的序列为12345、13452等42个。
*/
#include"Queue.h"
typedef struct sStack {
element data[max];
int top;
}seqStack;
void initialStack(seqStack& S) {
S.top = -1;
}
bool stackEmpty(seqStack& S) {
if (S.top == -1)
return true;
else
return false;
}
bool stackFull(seqStack& S) {
if (S.top == max - 1)
return true;
else
return false;
}
bool pushStack(seqStack& S, element x) {//入栈
if (stackFull(S))
return false;
else
{
S.top++;
S.data[S.top] = x;
return true;
}
}
bool popStack(seqStack& S, element& x) {//出栈
if (stackEmpty(S))
return true;
else {
x = S.data[S.top];
S.top--;
return true;
}
}
bool stackTop(seqStack& S, element& x) {//取栈顶元素
if (stackEmpty(S))
return false;
else {
x = S.data[S.top];
return true;
}
}
int fun(seQueue inQ, int n, seqStack& S, seQueue outQ) {
if (n <= 0 || queueEmpty(inQ) && queueEmpty(outQ) && stackEmpty(S)) {
return 0;
}
if (sizeQueue(inQ) == n) {
element x=0;//存放出队队列队头元素
while (!queueEmpty(outQ)) {
queueFront(outQ, x);
cout << x << " ";
outQueue(outQ);
}
cout << endl;
return 0;
}
//seqStack SCopy = S;
//seQueue QCopy = outQ;
element y;//存放栈顶元素
if (!stackFull(S)) {
stackTop(S, y);
enQueue(outQ, y);
popStack(S, y);
fun(inQ, n, S, outQ);
}
element z=0;//存放入队队列队头元素
if (!queueEmpty(inQ)) {
queueFront(inQ, z);
pushStack(S, z);
outQueue(inQ);
fun(inQ, n, S, outQ);
}
return 0;
}
int main() {
seQueue inQ, outQ;
seqStack S;
initialStack(S);
initQueue(inQ);
initQueue(outQ);
int n,a[100];
cout << "输入元素个数:";
cin >> n;
cout << "输入元素:" << endl;
for (int i = 0; i < n; i++) {
cin >> a[i];
enQueue(inQ, a[i]);
}
fun(inQ, n, S, outQ);
return 0;
}
头文件队列的相关运算如下
#include<iostream>
#include<stdlib.h>
using namespace std;
#define max 100
typedef int element;
typedef struct sQueue {
element data[max];
int front;
int rear;
}seQueue;
void initQueue(seQueue& Q) {
Q.front = 0;
Q.rear = 0;
}
bool queueEmpty(seQueue& Q) {
if (Q.front == Q.rear)
return true;
else
return false;
}
void queueFront(seQueue& Q, element x) {//取队头元素
if (queueEmpty(Q))
cout << "队空,不可取队头元素!";
else
x=Q.data[(Q.front + 1) % max] ;
}
void enQueue(seQueue& Q, element x) {//入队
Q.rear = ((Q.rear) + 1) % max;
Q.data[Q.rear] = x;
}
void outQueue(seQueue& Q) {//出队
Q.front = (Q.front + 1) % max;
}
int sizeQueue(seQueue& Q) {//求队列中元素个数
return (Q.rear - Q.front+max) % max;
}
编译没有问题,运行时输完数后,按回车什么都输不出来,这个我感觉有点难对我来说,这种写法也只是看到一个人的博客尝试一下,但我真的希望能搞出来,麻烦帮我看看哪里不合适,哪怕只是很小的一个地方,我也会认真改正