课时13作业

发布时间 2023-04-09 11:09:34作者: ha_1007

Description

新建一个栈,读取标准输入3个整数3 4 5,入栈3 4 5,依次出栈,打印 5 4 3,新建循环队列(Maxsize为5),读取标准输入3 4 5 6 7,入队7时,队满,打印false,然后依次出队,输出 3 4 5 6

Input

读取标准输入,内容依次是3 4 5,换行后,接着是3 4 5 6 7

Output

如果输入是3 4 5,换行,接着是3 4 5 6 7,那么输出是

5 4 3

false

3 4 5 6

注意每个数字占用两个字符的位置,5之前是有一个空格的,第三行的3之前也是有一个空格的

Sample Input 1 

3 4 5
3 4 5 6 7

Sample Output 1

 5 4 3
false
 3 4 5 6

Sample Input 2 

1 3 9
1 3 5 7 9

Sample Output 2

 9 3 1
false
 1 3 5 7
#include <stdio.h>
#include <stdlib.h>

//第13节课作业,针对栈,队列循环进行的练习
#define MaxSize 5
typedef int ElemType;
typedef struct {
    ElemType data[MaxSize];  //数组
    int top;                 //始终指向栈顶的一个变量
}SqStack;

//下面是循环队列的结构体

typedef struct {
    ElemType data[MaxSize];    //数组,存储MaxSize-1个元素
    int front,rear;   //队列头,队列尾
}SqQueue;

// 初始化栈
void InitStack(SqStack &S)
{
    S.top=-1;   //初始化栈就是S.top=-1,让栈为空
}

bool StackEmpty(SqStack S)
{
    if(-1==S.top)
    {
        return true;
    } else{
        return false;
    }
}

//入栈
bool Push(SqStack &S,ElemType x)
{
    //判断栈是否满了
    if(S.top==MaxSize-1)
    {
        return false;
    }
    S.data[++S.top]=x;
    //等价于
    //S.top=S.top+1;
    //S.data[S.top]=x;
    return true;
}

//弹栈
bool Pop(SqStack &S,ElemType &m)
{
    if(StackEmpty(S))
    {
        return false;
    }
    m=S.data[S.top--];
    //出栈
    //后减减等价于
    //m=S.data[S.top];
    //S.top=S.top-1;
    return true;
}

void InitQueue(SqQueue &Q)
{
    Q.front=Q.rear=0;    // 初始化循环队列,就是让头尾都指向零号
}

//判断循环队列是否为空
bool isEmpty(SqQueue Q)
{
    return Q.rear==Q.front;
}

//入队
bool EnQueue(SqQueue &Q,ElemType x)
{
    if((Q.rear+1)%MaxSize==Q.front)  //判断循环队列是否满了,满了就不能入队了
    {
        return false;
    }
    Q.data[Q.rear]=x;   //放入元素
    Q.rear=(Q.rear+1)%MaxSize;   //rear要加1,如果大于数组最大下标,回到开头
    return true;
}

//出队,
bool DeQueue(SqQueue &Q,ElemType &x)
{
    if(Q.rear==Q.front)   //队列为空,无法出队
    {
        return false;
    }
    x=Q.data[Q.front];   //出队
    Q.front=(Q.front+1)%MaxSize;
    return true;
}
int main() {
    int element ,i;
    SqStack S;
    for (int i = 0; i < 3; i++) {
        scanf("%d",&element);   //读取三个元素
        Push(S,element);
    }
    //出栈
    for (int i = 0; i < 3; i++) {
        Pop(S,element);
        printf("%2d",element);
    }
    printf("\n");
    SqQueue Q;
    InitQueue(Q);
    bool flag;     //接收是否入队成功

    for (int i = 0; i < 5; i++) {
        scanf("%d",&element);    //读取输入的5个元素
        flag=EnQueue(Q,element);
        if(false==flag)
        {
            printf("false\n");
        }
    }
    for (int i = 0; i < 4; i++) {
        DeQueue(Q,element);   //出队每个元素
        printf("%2d",element);
    }
    printf("\n");
    return 0;
}