用雙隊列模擬棧及用棧逆置隊列
阿新 • • 發佈:2019-05-05
出隊 print == int ret ise 初始 type lib
雙隊列模擬棧的基本操作
#include<stdio.h> #include<stdlib.h> #define maxsize 30 typedef int datatype; typedef struct{ datatype data[maxsize]; int front,rear; }SeqQueue; //置空棧 void Initial(SeqQueue *q1,SeqQueue *q2){ q1->front= 0,q1->rear = 0; q2->front = 0,q2->rear= 0; } int QueueIsEmpty(SeqQueue *q){ return q->rear == q->front; } int QueueIsFull(SeqQueue *q){ return q->front ==(q->rear+1)%maxsize; } int EnQueue(SeqQueue *q,datatype x){ if(QueueIsFull(q)) return 0; q->data[q->rear++] = x; return 1; } int DeQueue(SeqQueue *q,datatype *x){ if(QueueIsEmpty(q)) return 0; *x = q->data[q->front]; q->front = (q->front+1)%maxsize; return 1; } //判斷棧空 int StackIsEmpty(SeqQueue *q1,SeqQueue *q2){ return QueueIsEmpty(q1)&&QueueIsEmpty(q2); } //判斷棧滿 int StackIsFull(SeqQueue *q1,SeqQueue *q2){ return QueueIsFull(q1)||QueueIsFull(q2); } //進棧 int StackPush(SeqQueue *q1,SeqQueue *q2,datatype x){ if(StackIsFull(q1,q2)) return 0; if(StackIsEmpty(q1,q2)) EnQueue(q1,x); if(!QueueIsEmpty(q1)) EnQueue(q1,x); if(QueueIsEmpty(q1)) EnQueue(q2,x); return 1; } //出棧 int StackPop(SeqQueue *q1,SeqQueue *q2,datatype *x){ if(StackIsEmpty(q1,q2)) //判斷棧空 return 0; if(!QueueIsEmpty(q1)){ //若q1不為空 while(!QueueIsEmpty(q1)){ DeQueue(q1,x); //出q1 EnQueue(q2,*x); //進q2 } } else //若q1為空 while(!QueueIsEmpty(q2)){ DeQueue(q2,x); //出q2 EnQueue(q1,*x); //進q1 } return 1; }
用棧逆置隊列
#include<stdio.h> #include<stdlib.h> #define maxsize 30 typedef int datatype; typedef struct{ datatype data[maxsize]; int top; }SeqStack; typedef struct{ datatype data[maxsize]; int front,rear; }SeqQueue; //初始化棧和隊列 void Initial(SeqStack *s,SeqQueue *q){ s->top = -1; q->front = 0,q->rear = 0; printf("初始化成功\n"); } //判斷隊滿 int QueueFull(SeqQueue *q){ return q->front == (q->rear+1)%maxsize; } //判斷隊空 int QueueEmpty(SeqQueue *q){ return q->rear == q->front; } //出隊 int DeQueue(SeqQueue *q,datatype *x){ if(QueueEmpty(q)) return 0; x = &q->data[q->front]; q->front = (q->front+1)%maxsize; return 1; } //進隊 int EnQueue(SeqQueue *q,datatype x){ if(QueueFull(q)) return 0; q->data[q->rear++] = x; return 1; } //判斷棧滿 int IsFull(SeqStack *s){ return s->top == maxsize-1; } //判斷棧空 int IsEmpty(SeqStack *s){ return s->top == -1; } //進棧 int Push(SeqStack *s,datatype x){ if(IsFull(s)) return 0; s->data[++s->top] = x; return 1; } //出棧 int Pop(SeqStack *s,datatype *x){ if(IsEmpty) return 0; x = &s->data[s->top]; return s->data[s->top--]; } //隊列逆置 void Reverse(SeqStack *s,SeqQueue *q){ datatype x; while(!QueueEmpty(q)){ x = DeQueue(q,&x); Push(s,x); } while(!IsEmpty(s)){ x = Pop(s,&x); EnQueue(q,x); } } int main(){ SeqStack *s = (SeqStack*)malloc(maxsize*sizeof(SeqStack)); SeqQueue *q = (SeqQueue*)malloc(maxsize*sizeof(SeqQueue)); Initial(s,q); int x = 0,i; //給隊列賦值 printf("請輸入進隊元素\n"); scanf("%d",&i); while(i!=-1){ EnQueue(q,i); scanf("%d",i); } Reverse(s,q); while(!QueueEmpty(q)){ printf("隊列中的元素分別為:%d",q->data[q->front--]); } }
用雙隊列模擬棧及用棧逆置隊列