作者pthread (QQ)
看板Examination
标题Re: [考题] 程式语言/98身心障碍
时间Tue Mar 12 15:58:35 2013
分享这题的程式码
方法是从堆叠拿出的书放入伫列
放回去的时候再从伫列取出放回堆叠
最後再放回所阅读的书
程式码很长,不知道有更简洁的写法吗?
是用dev c++开发的
#include<iostream>
#define N 50
using namespace std;
struct Node{
int number;
char name[10];
};
struct Stack{
Node *stackpointer[N];
int sp;
};
struct Queue{
Node *queuepointer[N];
int rear;
int front;
};
int isempty(Stack *);
void push(Stack *,Node *);
Node* pop(Stack *);
void printBook(Stack *);
void readBook(Stack *,Queue *,int);
bool isQueueEmpty(Queue *);
void enQueue(Queue *,Node *);
Node* deQueue(Queue *);
int main(){
Stack s;
Queue q;
s.sp=-1;
q.rear=-1;
q.front=-1;
Node *ptr=new Node;
strcpy(ptr->name,"书本5");
ptr->number=5;
push(&s,ptr);
ptr=new Node;
strcpy(ptr->name,"书本4");
ptr->number=4;
push(&s,ptr);
ptr=new Node;
strcpy(ptr->name,"书本3");
ptr->number=3;
push(&s,ptr);
ptr=new Node;
strcpy(ptr->name,"书本2");
ptr->number=2;
push(&s,ptr);
ptr=new Node;
strcpy(ptr->name,"书本1");
ptr->number=1;
push(&s,ptr);
cout<<"书本原始序列:"<<endl;
printBook(&s);
cout<<"input read serial(请输入3本书):\n";
int input[3];
int tmp;
for(int i=0;i<3;i++){
cin>>tmp;
input[i]=tmp;
}
for(int i=0;i<3;i++){
switch(input[i]){
case 1:
cout<<endl;
readBook(&s,&q,1);
printBook(&s);
break;
case 2:
cout<<endl;
readBook(&s,&q,2);
printBook(&s);
break;
case 3:
cout<<endl;
readBook(&s,&q,3);
printBook(&s);
break;
case 4:
cout<<endl;
readBook(&s,&q,4);
printBook(&s);
break;
case 5:
cout<<endl;
readBook(&s,&q,5);
printBook(&s);
break;
}
}
system("pause");
return 0;
}
void push(Stack *p,Node *x){
p->sp++;
p->stackpointer[p->sp]=x;
}
Node* pop(Stack *p){
if(isempty(p))
cout<<"堆叠已空"<<endl;
else
return p->stackpointer[p->sp--];
}
int isempty(Stack *p){
if(p->sp==-1)
return 1;
else
return 0;
}
void enQueue(Queue *p,Node *x){
p->rear++;
p->queuepointer[p->rear]=x;
}
Node* deQueue(Queue *p){
p->front++;
return p->queuepointer[p->front];
}
bool isQueueEmpty(Queue *p){
if(p->rear==p->front)
return true;
else
return false;
}
void printBook(Stack *p){
for(int i=p->sp;i>=0;i--){
cout<<p->stackpointer[i]->name<<endl;
}
}
void readBook(Stack *s,Queue *q,int x){
Node *tmp;
Node *readbook;
bool flag=false;
for(int i=s->sp;i>=0&&flag==false;i--){
if(s->stackpointer[i]->number!=x){
tmp=pop(s);
enQueue(q,tmp);
}
else{
cout<<"读了这本书: "<<s->stackpointer[i]->name<<endl;
readbook=pop(s);
flag=true;
}
}
while(!isQueueEmpty(q)){
tmp=deQueue(q);
push(s,tmp);
}
push(s,readbook);
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 111.246.201.24