一、思路:1、創建兩個空棧A和B;2、A棧作為隊列的入口,B棧作為隊列的出口;3、入隊列操作:即是入棧A;4、出隊列操作:若棧B為空,則將A棧內容出棧並壓人B棧,再出 B棧;不為空就直接出棧;
二、代碼:
1、頭文件:stack_to_queue.h:封裝了:隊列、棧的數據結構和各種操作的函數。
1 #ifndef STACK_TO_QUEUE_H 2 #define STACK_TO_QUEUE_H 3 4 #include<stdio.h> 5 #include<stdlib.h> 6 7 #define ALLOC_SIZE 512 8 #define ElemType int 9 10 typedef struct sqstack 11 { 12 ElemType *top; //棧頂指針 13 ElemType *base; //棧底指針 14 int stack_size; //棧目前能存儲的元素數目 15 }SqStack; //順序棧 16 17 typedef struct sqqueue 18 { 19 SqStack front; //隊列頭,出口, 20 SqStack rear; //隊列尾,入口 21 }SqQueue; 22 23 /*棧的初始化函數*/ 24 void InitStack(SqStack *s) 25 { 26 if((s->top=(ElemType*)malloc(ALLOC_SIZE*sizeof(ElemType)))==NULL) 27 { 28 printf("stack malloc error\n"); 29 exit(1); 30 } 31 s->base=s->top; 32 s->stack_size=ALLOC_SIZE; 33 } 34 35 /*出棧函數,棧為空時返回0,成功出棧時返回1*/ 36 int pop_stack(SqStack *s,ElemType *data) 37 { 38 if(s->top!=s->base) 39 { 40 s->top--; 41 *data=*s->top; 42 return 1; 43 } 44 else //返回值為0,表示棧為空 45 { 46 return 0; 47 } 48 } 49 50 /*入棧函數*/ 51 void push_stack(SqStack *s,ElemType data) 52 { 53 if((s->top-s->base)>=s->stack_size) 54 { 55 if((s->base=(ElemType *)realloc(s->base,(s->stack_size+ALLOC_SIZE)*sizeof(ElemType)))==NULL) 56 { 57 printf("stack realloc error\n"); 58 exit(1); 59 } 60 else 61 { 62 s->top=s->base+s->stack_size; 63 s->stack_size+=ALLOC_SIZE; 64 } 65 } 66 *(s->top)=data; 67 s->top++; 68 } 69 70 /*隊列初始化函數*/ 71 void InitQueue(SqQueue *q) 72 { 73 SqStack A,B; 74 75 InitStack(&A); 76 InitStack(&B); 77 q->front=B; //將棧B作為隊列的出口 78 q->rear=A; //將棧A作為隊列的入口 79 } 80 81 /*入隊列函數*/ 82 void push_queue(SqQueue *q,ElemType data) 83 { 84 push_stack(&q->rear,data); 85 } 86 87 /*出隊列函數,隊列為空時返回0,成功出隊列返回1*/ 88 int pop_queue(SqQueue *q,ElemType *data) 89 { 90 if((pop_stack(&q->front,data))==0) //如果作為出口的棧為空,就將入口棧的內容壓入 91 { 92 while((pop_stack(&q->rear,data))!=0) 93 { 94 push_stack(&q->front,*data); 95 } 96 } 97 else //否則,返回1 98 { 99 return 1; 100 } 101 if((pop_stack(&q->front,data))==0) //如果將入口棧的內容壓人后還為空,說明此時隊列為空 102 { 103 return 0; 104 } 105 else 106 { 107 return 1; 108 } 109 } 110 #endif
2、主函數:main.c:只為測試用,通過for循環讓1000個數0-999入隊列,再打印。
1 #include<stdio.h> 2 #include"stack_to_queue.h" 3 4 int main() 5 { 6 SqQueue q; 7 int i,data; 8 9 InitQueue(&q); 10 for(i=0;i<1000;i++) 11 { 12 push_queue(&q,i); 13 } 14 while((pop_queue(&q,&data))!=0) 15 { 16 printf("%d ",data); 17 } 18 19 return 0; 20 }
之前寫的時候犯了一個錯誤,在stack_to_queue.h中的62行,使用realloc函數重新分配內存后,要將top指針也指向新的位置,我漏掉了這一步,導致出錯,檢查了很久,最后的解決過程在這:http://q.cnblogs.com/q/54337/
