#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable:4996)
#define MAX 100
struct Queue {
int front;
int rear;
int* base;
};
int Size(struct Queue Q); //队列求长度
void InitQ(struct Queue* Q); //初始化队列
void EnQueue(struct Queue* Q, int e); //入队
void bianli(struct Queue Q); //遍历
int DeQueue(struct Queue* Q); //出队
int EmptyQ(struct Queue Q); //队列为空返回0,非空返回1
int FullQ(struct Queue Q); //队列为满返回1,非满返回0
struct Sqsack {
struct Queue Q1;
struct Queue Q2;
};
void InitS(struct Sqsack* S);
void Push(struct Sqsack* S, int e);
void Pop(struct Sqsack* S);
int EmptyS(struct Sqsack* S);
int FullS(struct Sqsack* S);
int main()
{
struct Sqsack S;
InitS(&S);
Push(&S, 1);
Push(&S, 2);
Push(&S, 3);
Pop(&S);
Pop(&S);
Pop(&S);
/*
int i = 0;
struct Queue Q;
InitQ(&Q);
EnQueue(&Q, 1);
EnQueue(&Q, 2);
EnQueue(&Q, 3);
bianli(Q);
//i = DeQueue(&Q);
//printf("出队数据为 = %d\n", i);
*/
return 0;
}
void InitQ(struct Queue* Q)
{
Q->base = (int*)malloc(MAX * sizeof(int));
if (Q->base == NULL)
{
printf("开辟空间失败\n");
}
else
{
Q->front = 0;
Q->rear = 0;
printf("开辟空间成功\n");
}
}
void EnQueue(struct Queue* Q, int e)
{
if ((Q->rear + 1) % MAX == Q->front)
{
printf("队已满\n");
}
else
{
Q->base[Q->rear] = e;
Q->rear = (Q->rear + 1) % MAX;
}
}
void bianli(struct Queue Q)
{
int e = 0;
if (Q.front == Q.rear)
{
printf("队列为空\n");
}
else
{
while (Q.front != Q.rear)
{
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAX;
printf("队中数据为 = %d\n",e);
}
}
}
int Size(struct Queue Q)
{
return (Q.rear - Q.front + MAX) % MAX;
}
int DeQueue(struct Queue* Q)
{
int e = 0;
if (Q->front == Q->rear)
{
printf("队列为空\n");
}
else
{
e = Q->base[Q->front];
Q->front = (Q->front + 1) % MAX;
return e;
}
}
int EmptyQ(struct Queue Q) //队列为空返回0,非空返回1
{
if ((Q.rear - Q.front + MAX) % MAX == 1) //如果剩一个数据则返回3
{
return 3;
}
if (Q.rear == Q.front)
{
return 0;
}
else
{
return 1;
}
}
int FullQ(struct Queue Q) //队列为满返回1,非满返回0
{
if ((Q.rear + 1) % MAX == Q.front)
{
return 1;
}
else
{
return 0;
}
}
// 栈操作!!!!!!!!!!!!!
void InitS(struct Sqsack* S)
{
InitQ(&S->Q1);
InitQ(&S->Q2);
}
void Push(struct Sqsack* S, int e)
{
if (FullQ(S->Q1))
{
printf("队列1有数据\n");
}
else
{
EnQueue(&S->Q1, e);
}
}
void Pop(struct Sqsack* S)
{
int e = 0;
if (EmptyQ(S->Q1))
{
while (EmptyQ(S->Q1) != 3)
{
e = DeQueue(&S->Q1);
EnQueue(&S->Q2, e);
}
e = DeQueue(&S->Q1); //将最后一个数输出出去
printf("出队数据为 = %d\n", e);
}
else
{
while (EmptyQ(S->Q2) != 3)
{
e = DeQueue(&S->Q2);
EnQueue(&S->Q1, e);
}
e = DeQueue(&S->Q2); //将最后一个数输出出去
printf("出队数据为 = %d\n", e);
}
}
int EmptyS(struct Sqsack* S)
{
if (!EmptyQ(S->Q1) && !EmptyQ(S->Q1)) // 空栈返回1
{
return 1;
}
}
int FullS(struct Sqsack* S) // Q1主队满就算栈满
{
if (FullQ(S->Q1))
{
return 1;
}
}
两个顺序队实现栈—版本2 c语言实现
于 2023-03-29 16:44:08 首次发布