用两个栈来模拟一个队列的,进队和出队,写的很烂,大家多批评,多给意见,谢谢了先.....
/*
*implement a stack in c
*and make two stack as a queue
*Date:2012.05.03
*/
#define STACK_INIT_SIZE 10
#define STACK_INCREMENT 2
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef int ElemType;
typedef int Status;
typedef struct SqStack{
ElemType *base;
ElemType *top;
int stackSize;
}SqStack;
typedef struct Queue{
SqStack *inStack;
SqStack *outStack;
}Queue;
//traverse the stack from base to top
void print(SqStack *s){
assert(s);
ElemType *elem = s->base;
if(s->base == s->top){
printf("This is an empty stack!\n");
}
for(elem ; elem != s->top ; elem++){
printf("element is %d", *elem);
printf("\n");
}
}
//init statck
SqStack* InitStack(SqStack *s){
s = (SqStack*)malloc(sizeof(SqStack));
if(!s)
exit(0);
s->base = (ElemType*)malloc(STACK_INIT_SIZE*sizeof(ElemType));
s->top = s->base;
s->stackSize = STACK_INIT_SIZE;
printf("Init stack successfully!\n");
return s;
}
//free stack
Status FreeStack(SqStack *s){
if(!s){
printf("Stack is null no need to free!\n");
return 0;
}else{
free(s->base);
free(s);
return 1;
}
}
//push element into stack
Status Push(SqStack *s, ElemType e){
assert(s);
//stack is full, need more space
if(s->top - s->base >= s->stackSize){
s->base = (ElemType*)realloc(s->base, (s->stackSize + STACK_INCREMENT)*sizeof(ElemType));
if(!s->base){
printf("realloc failed!\n");
exit(1);
}
s->top = s->base + s->stackSize;
s->stackSize += STACK_INCREMENT;
}
//*s->top++ = e equals the two sentances as follows
*s->top = e;
++s->top;
return 1;
}
//pop out elem from stack
Status Pop(SqStack *s, ElemType **e){
assert(s);
if(s->base == s->top){
printf("It's a empty stack\n");
return 0;
}
//*e = --s->top; equals the two sentances as follows
--s->top;
*e = s->top;
printf("in Pop statck elem = %d\n", **e);
return 1;
}
//enqueue an element to the queue
Status Enqueue(Queue *q, ElemType e){
printf("The elem Enqueue is %d\n", e);
assert(q);
return Push(q->inStack, e);
}
//dequeue an element from the queue
Status Dequeue(Queue *q, ElemType **elem){
assert(q);
//pop from the inStack first
Pop(q->inStack, elem);
//printf("The elem pop out is %d\n", **elem);
//then push into the outStack
Push(q->outStack, **elem);
//pop out from the queue
Pop(q->outStack, elem);
}
//init the queue made by two stacks
Queue* InitQueue(Queue *q){
q = (Queue*)malloc(sizeof(Queue));
q->inStack = InitStack(q->inStack);
q->outStack = InitStack(q->outStack);
return q;
}
void main(){
int i;
//code below is used to test the two-stack-queue
Queue *q;
q = InitQueue(q);
//insert some elem to the queue
for(i = 0 ; i < 10 ; i++){
Enqueue(q, i);
}
//print Queue
printf("will print the Queue below! \n");
print(q->inStack);
for(i = 0 ; i < 10 ; i++){
ElemType *e;
//printf("elem---before = %ld \n", e);
Dequeue(q, &e);
printf("elem dequeued is %d\n", *e);
}
}
![](https://img-my.csdn.net/uploads/201205/06/1336291940_7393.jpg)