用栈逆置队列

//已知q 是一非空队列,编写一个算法,
//仅用队列和栈及少量工作变量完成将队列q 中的所有元素逆置
#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 30
typedef struct
{
	char data[MAXSIZE];
	int top;                          //栈顶指针
}SeqStack;                            //顺序栈类型

void Init_SeqStack(SeqStack **s)
{
	(*s) = (SeqStack *)malloc(sizeof(SeqStack));
	(*s)->top = -1;
}

int Empty_SeqStack(SeqStack *s)
{
	if (s->top == -1)
	{
		return 1;
	}
	return 0;
}

void Push_SeqStack(SeqStack *s, char x)
{
	if (s->top == MAXSIZE - 1)
	{
		printf("The stack is full!\n");
	}
	else
	{
		s->top++;
		s->data[s->top] = x;
	}
}

void Pop_SeqStack(SeqStack *s, char *x)
{
	if (s->top == -1)
	{
		printf("Stack is empty!\n");
	}
	else
	{
		*x = s->data[s->top];
		s->top--;
	}
}

typedef struct
{
	char data[MAXSIZE];                  //栈中元素存储空间
	int rear, front;                     //队尾和对头指针
}SeQueue;

void Init_SeQueue(SeQueue **q)           //循环队列初始化
{
	*q = (SeQueue *)malloc(sizeof(SeQueue));
	(*q)->front = 0;
	(*q)->rear = 0;
}

int Empty_SeQueue(SeQueue *q)            //判断队列空
{
	if (q->front == q->rear)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

void In_SeQueue(SeQueue *s, char x)         //元素入队
{
	if ((s->rear + 1) % MAXSIZE == s->front)
	{
		printf("The Queue is full!\n");
	}
	else
	{
		s->rear = (s->rear + 1) % MAXSIZE;
		s->data[s->rear] = x;
	}
}

void Out_SeQueue(SeQueue *s, char *x)       //元素出队
{
	if (s->front == s->rear)
	{
		printf("The Queue is empty!\n");
	}
	else
	{
		s->front = (s->front + 1) % MAXSIZE;
		*x = s->data[s->front];
	}
}

void print(SeQueue *s)
{
	int i;
	i = (s->front + 1) % MAXSIZE;
	while (i != s->rear)
	{
		printf("%4c", s->data[i]);
		i = (i + 1) % MAXSIZE;
	}
	printf("%4c\n", s->data);
}

void Revers_Queue(SeQueue *q, SeqStack *s)
{
	char x, *p = &x;                      //用栈s 逆置队列
	Init_SeqStack(&s);
	while (!Empty_SeQueue(q))             //当队列*q 非空时
	{
		Out_SeQueue(q, p);                //取出对头元素*p
		Push_SeqStack(s, *p);             //将对头元素*p 压入栈s
	}

	while (!Empty_SeqStack(s))            //当栈s 非空时
	{
		Pop_SeqStack(s, p);               
		In_SeQueue(q, *p);
	}
}

int main()
{
	SeqStack *s;
	SeQueue *q;
	char x, *y = &x;
	Init_SeqStack(&s);
	Init_SeQueue(&q);

	if (Empty_SeQueue(q))
	{
		printf("Queue is empty!\n");
	}
	
	printf("Input any string:\n");
	scanf("%c", &x);
	while (x != '\n')
	{
		In_SeQueue(q, x);
		scanf("%c", &x);
	}

	printf("Output elements of Queue:\n");
	print(q);
	
	printf("Convert Queue:\n");	
	Revers_Queue(q, s);
	printf("Output elements of Queue:\n");
	print(q);

	return 0;
}

  • 9
    点赞
  • 48
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值