#include<stdio.h>
#include<stdlib.h>
/*定义ElemType*/
typedef int ElemType;
/*定义堆栈体*/
typedef struct stack
{
int top; //栈顶指示器
int maxSize; //栈的最大容量
ElemType* element;
}Stack;
/*定义队列体*/
typedef struct queue
{
int front; //队列头指示器
int rear; //队列尾指示器
int maxSize; //队列最大容量
ElemType* element;
}Queue;
/*创建堆栈*/
void Create_Stack(Stack* S, int mSize)
{
S->maxSize = mSize;
S->element = (ElemType*)malloc(sizeof(ElemType) * mSize);
S->top = -1;
}
/*销毁堆栈*/
void Destroy_Stack(Stack* S)
{
S->maxSize = 0;
free(S->element);
S->top = -1;
}
/*堆栈判空*/
bool IsEmpty_Stack(Stack* S)
{
return S->top == -1;
}
/*堆栈判满*/
bool IsFull_Stack(Stack* S)
{
return S->top == S->maxSize - 1;
}
/*取出栈顶元素*/
bool Top_Stack(Stack* S, ElemType* x)
{
if (IsEmpty_Stack(S))
return false;
*x = S->element[S->top];
return true;
}
/*入栈操作*/
bool Push_Stack(Stack* S, ElemType x)
{
if (IsFull_Stack(S))
return false;
S->top++;
S->element[S->top] = x;
return true;
}
/*出栈操作*/
bool Pop_Stack(Stack* S)
{
if (IsEmpty_Stack(S))
return false;
S->top--;
return true;
}
/*创建队列*/
void Create_Queue(Queue* Q, int mSize)
{
Q->maxSize = mSize;
Q->element = (ElemType*)malloc(sizeof(ElemType) * mSize);
Q->front = Q->rear = 0;
}
/*销毁队列*/
void Destroy_Queue(Queue* Q)
{
Q->maxSize = 0;
free(Q->element);
Q->front = Q->rear = -1;
}
/*队列判空*/
bool IsEmpty_Queue(Queue* Q)
{
return Q->front == Q->rear;
}
/*队列判满*/
bool IsFull_Queue(Queue* Q)
{
return (Q->rear + 1) % (Q->maxSize) == Q->front;
}
/*获取队头元素*/
bool Front_Queue(Queue* Q, ElemType* x)
{
if (IsEmpty_Queue(Q))
return false;
*x= Q->element[(Q->front + 1) % Q->maxSize];
return true;
}
/*入队操作*/
bool EnQueue(Queue* Q, ElemType x)
{
if (IsFull_Queue(Q))
return false;
Q->rear = (Q->rear + 1) % Q->maxSize;
Q->element[Q->rear] = x;
return true;
}
/*出队操作*/
bool DeQueue(Queue* Q)
{
if (IsEmpty_Queue(Q))
return false;
Q->front = (Q->front + 1) % Q->maxSize;
return true;
}
/*排序操作函数*/
void Sort(Stack* S, Queue* Q)
{
ElemType* x = (ElemType*)malloc(sizeof(ElemType));
for (S->top = S->maxSize - 1; S->top > -1; )
{
Top_Stack(S, x);
Pop_Stack(S);
EnQueue(Q, *x);
}
/*至此,堆栈中的所有元素都已进入队列*/
for (Q->front = 0; Q->front < Q->rear; (Q->front % +1) % Q->maxSize)
{
Front_Queue(Q, x);
DeQueue(Q);
Push_Stack(S, *x);
}
}
/*主函数*/
int main()
{
/*创建堆栈、队列并初始化*/
Stack S;
Queue Q;
Create_Stack(&S, 5);
Create_Queue(&Q, 6);
/*向栈中输入元素*/
Push_Stack(&S, 1);
Push_Stack(&S, 5);
Push_Stack(&S, 9);
Push_Stack(&S, 6);
Push_Stack(&S, 7);
/*堆栈中信息输出*/
printf("现在堆栈中的元素为(从栈顶向栈底输出): \n");
for (S.top = S.maxSize - 1; S.top > -1; S.top--)
{
printf("%d\n", S.element[S.top]);
}
/*进行逆置操作*/
Sort(&S, &Q);
/*堆栈中信息输出*/
printf("现在堆栈中的元素为(从栈顶向栈底输出): \n");
for (S.top = S.maxSize - 1; S.top > -1; S.top--)
{
printf("%d\n", S.element[S.top]);
}
/*操作结束后释放申请的空间*/
Destroy_Stack(&S);
Destroy_Queue(&Q);
}
【数据结构】2020.09.24作业:利用队列将栈中元素逆置
最新推荐文章于 2022-10-08 15:28:15 发布