PTA练习题
基础实验3-2.5 堆栈模拟队列 (25 分)
设已知有两个堆栈S1和S2,请用这两个堆栈模拟出一个队列Q。
所谓用堆栈模拟队列,实际上就是通过调用堆栈的下列操作函数:
int IsFull(Stack S):判断堆栈S是否已满,返回1或0;
int IsEmpty (Stack S ):判断堆栈S是否为空,返回1或0;
void Push(Stack S, ElementType item ):将元素item压入堆栈S;
ElementType Pop(Stack S ):删除并返回S的栈顶元素。
实现队列的操作,即入队void AddQ(ElementType item)和出队ElementType DeleteQ()。
输入格式:
输入首先给出两个正整数N1和N2,表示堆栈S1和S2的最大容量。随后给出一系列的队列操作:A item表示将item入列(这里假设item为整型数字);D表示出队操作;T表示输入结束。
输出格式:
对输入中的每个D操作,输出相应出队的数字,或者错误信息ERROR:Empty。如果入队操作无法执行,也需要输出ERROR:Full。每个输出占1行。
输入样例:
3 2
A 1 A 2 A 3 A 4 A 5 D A 6 D A 7 D A 8 D D D D T
输出样例:
ERROR:Full
1
ERROR:Full
2
3
4
7
8
ERROR:Empty
这题是要我们用一大一小两个堆栈模拟队列,我这里用的是堆栈链式存储模拟队列,用堆栈的顺序存储同样能实现,代码有注释。
// An highlighted block
#include<stdio.h>
#include<stdlib.h>
typedef struct SNode *Stack;
struct SNode{
int data;
int top;
struct SNode *next;
};
Stack Create();
int IsEmpty(Stack s);
void Push(int item, Stack s);
int Pop(Stack s);
int Top(Stack s);
void exchange(Stack s1,Stack s2);
int main()
{
int num1,num2,n1,n2;
scanf("%d%d",&num1,&num2);
if(num1>num2){
n1=num2;
n2=num1;
}
else{n1=num1;n2=num2;}
Stack s1,s2;
s1=Create();
s2=Create();
//s1作为容量小的堆栈,s2作大的堆栈
char c;
int n;
scanf("%c",&c);
while(c!='T'){
if(c=='D'){
if(IsEmpty(s2)==0){
printf("%d\n",Pop(s2));
}
else if(IsEmpty(s1)==1&&IsEmpty(s2)==1) printf("ERROR:Empty\n");
else{
while(IsEmpty(s1)==0){
exchange(s1,s2);
}
printf("%d\n",Pop(s2));
}
}
if(c=='A'){
scanf("%d",&n);
if(Top(s1)==n1){
if(IsEmpty(s2)==1){ //s1满,s2空,把s1一个个放到s2里
while(IsEmpty(s1)==0){
exchange(s1,s2);
}
Push(n,s1);
}
else printf("ERROR:Full\n");
}
else Push(n,s1);
}
scanf("%c",&c);
}
return 0;
}
Stack Create(){
//创建一个空堆栈s
Stack s;
s=(Stack)malloc(sizeof(struct SNode));
s->top=0;
s->next=NULL;
return s;
}
int IsEmpty(Stack s){
//判断堆栈是否为空,空则返回1,不空返回0
return (s->next==NULL);
}
void Push(int item, Stack s){
//把item压入堆栈顶
struct SNode *tmpcell;
tmpcell=(struct SNode *)malloc(sizeof(struct SNode));
if(s->next==NULL){tmpcell->top=1;}
else {
int i=s->next->top;
tmpcell->top=++i;
}
tmpcell->next=s->next;
s->next=tmpcell;
tmpcell->data=item;
}
int Pop(Stack s){
//删除并返回被删掉的栈顶元素data
Stack firstcell;
int n;
firstcell=s->next;
s->next=firstcell->next;
n=firstcell->data;
return n;
}
int Top(Stack s){
//返回栈顶top
if(s->next!=NULL) return (s->next->top);
else return s->top;
}
void exchange(Stack s1,Stack s2){
//把s1栈顶元素放到s2
Stack cup,p;
cup=(Stack)malloc(sizeof(struct SNode));
p=(Stack)malloc(sizeof(struct SNode));
cup=s1->next;
s1->next=cup->next;
cup->next=NULL;
if(s2->next==NULL) s2->next=cup;
else{
p=s2->next;
cup->next=p;
s2->next=cup;
}
}