用栈逆置队列

来源:互联网 发布:淘宝网电脑不能登录 编辑:程序博客网 时间:2024/05/20 06:24
//已知q 是一非空队列,编写一个算法,//仅用队列和栈及少量工作变量完成将队列q 中的所有元素逆置#include <stdio.h>#include <stdlib.h>#define MAXSIZE 30typedef 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);                //取出对头元素*pPush_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;}