本题采用c语言实现。由于此题要求将栈与队列结合应用,只是基础题目,所以我选择熟悉一下不同风格的实现方法,本文队列和栈采用结构体定义,且操作除初始化外均用函数实现。希望也能从简单的程序中学会有用的知识。
【问题描述】
已知Q是一个非空队列,S是一个空栈。仅使用少量工作变量以及对队列和栈的基本操作,编写一个算法,将队列Q中的所有元素逆置。
【输入形式】
输入的第一行为队列元素个数,第二行为队列从首至尾的元素
【输出形式】
输出队列的逆置
【样例输入】
3
1 2 3
【样例输出】
3 2 1
【评分标准】
需采用队列与栈的知识,否则不能得分
思路:
(1)将元素输入队列中
(2)以队列的“先进先出”方式输出各元素并依次插入到栈中
(3)采用栈的“后进先出”模式输出各元素,实现逆置
一、首先对栈和队列实现类型定义
由于队列最常用的为循环队列,为了更好的熟悉知识,本文采用循环队列解题。注意:循环队列一定不要忘记取模操作
typedef struct Queue//队列的尾指针指向最后一个元素的下一个位置,头指针指向首元素
{
int *base;
int front;
int rear;
}Queue;
typedef struct Stack//栈的尾指针指向最后一个元素,头指针指向首元素的下一个位置
{
int *base;
int *top;
int stacksize;
}Stack;
二、实现相应函数操作
注意:由于C语言中没有类似于C++的引用方式传递参数,所以为了实现地址传递,需要在形参中使用指针
1、入队:
//入队
Status insertQueue(Queue *Q, int *e)
{
if (((*Q).rear + 1) % MAXSIZE ==(*Q).front)
{
return ERROR;
}
(*Q).base[(*Q).rear] = *e;
(*Q).rear = ((*Q).rear + 1) % MAXSIZE;
return OK;
}
2、出队
//出队
Status popQueue(Queue *Q, int *e)
{
if ((*Q).rear == (*Q).front)
{
return ERROR;
}
*e = (*Q).base[(*Q).front];
(*Q).front = ((*Q).front + 1) % MAXSIZE;
return OK;
}
3、入栈
//入栈
Status insertStack(Stack *S, int *e)
{
if ((*S).top - (*S).base >= (*S).stacksize)
{
return ERROR;
}
*(*S).top = *e;
(*S).top = (*S).top + 1;
return OK;
}
4、取栈顶元素
//取栈顶元素
int Gettop(Stack *S)
{
if ((*S).top == (*S).base)
{
return ERROR;
}
(*S).top = (*S).top - 1;
int e = *(*S).top;
return e;
}
采用Status实现函数返回状态值
完整代码如下(附注释)
#include
#include
#define MAXSIZE 100000
typedef int Status;
#define OK 1
#define ERROR 0
typedef struct Queue
{
int *base;
int front;
int rear;
}Queue;
typedef struct Stack
{
int *base;
int *top;
int stacksize;
}Stack;
//入队
Status insertQueue(Queue *Q, int *e)
{
if (((*Q).rear + 1) % MAXSIZE ==(*Q).front)
{
return ERROR;
}
(*Q).base[(*Q).rear] = *e;
(*Q).rear = ((*Q).rear + 1) % MAXSIZE;
return OK;
}
//出队
Status popQueue(Queue *Q, int *e)
{
if ((*Q).rear == (*Q).front)
{
return ERROR;
}
*e = (*Q).base[(*Q).front];
(*Q).front = ((*Q).front + 1) % MAXSIZE;
return OK;
}
//入栈
Status insertStack(Stack *S, int *e)
{
if ((*S).top - (*S).base >= (*S).stacksize)
{
return ERROR;
}
*(*S).top = *e;
(*S).top = (*S).top + 1;
return OK;
}
//取栈顶元素
int Gettop(Stack *S)
{
if ((*S).top == (*S).base)
{
return ERROR;
}
(*S).top = (*S).top - 1;
int e = *(*S).top;
return e;
}
int main()
{
Queue Q; //队列初始化
Q.base = (int*)malloc(MAXSIZE * sizeof(int));
Q.rear = Q.front = 0;
Stack S; //栈初始化
S.base = (int*)malloc(MAXSIZE * sizeof(int));
S.top = S.base;
S.stacksize = MAXSIZE;
int n, i, e;
scanf("%d", &n);
for (i = 0; i < n; i++)
{
scanf("%d", &e);
if (insertQueue(&Q, &e) == ERROR)
{
exit(-1);
}
}
while (Q.rear != Q.front)
{
if (popQueue(&Q, &e) == ERROR)
{
exit(-1);
}
if (insertStack(&S, &e) == ERROR)
{
exit(-1);
}
}
while (S.top != S.base)//输出各元素
{
printf("%d ", Gettop(&S));
}
return 0;
}
越努力,越幸运
希望能更好的了解知识呦,end~~~