Re: [考題] 程式語言/98身心障礙

看板Examination作者 (QQ)時間12年前 (2013/03/12 15:58), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/2 (看更多)
分享這題的程式碼 方法是從堆疊拿出的書放入佇列 放回去的時候再從佇列取出放回堆疊 最後再放回所閱讀的書 程式碼很長,不知道有更簡潔的寫法嗎? 是用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
文章代碼(AID): #1HFk0kMu (Examination)
文章代碼(AID): #1HFk0kMu (Examination)