目录
一、栈的基本结构及其接口
二、我的队列结构定义
三、我的队列创建及其初始化
四、我的队列入队
五、我的队列出队
六、我的队列取队头元素
七、我的队列判空
八、我的队列销毁
一、栈的基本结构及其接口
//栈的结构定义
typedef int STDataType;typedef struct Stack{STDataType *a;int top;int capacity;
}ST;//栈的初始化
void STInit(ST* pst)
{pst->a=NULL;pst->top=0;pst->capacity=0;
}//栈的扩容
void checkcapacity(ST* pst)
{if(pst->top==pst->capacity){int newcapacity=pst->capacity==0?4:pst->capacity*4;STDataType* tmp=(STDataType*)realloc(pst->a,sizeof(STDataType)*newcapacity);if(tmp==NULL){perror("realloc fail");exit(-1);}pst->a=tmp;pst->capacity=newcapacity;}
}//入栈
void STPush(ST* pst,STDataType x)
{assert(pst);checkcapacity(pst);pst->a[pst->top++]=x;
}//出栈
void STPop(ST* pst)
{assert(pst);assert(pst->top);//空栈pst->top--;
}//取栈顶元素
STDataType STTop(ST* pst)
{assert(pst);assert(pst->top);//空栈return pst->a[pst->top-1];
}//判断栈是否为空
bool STEmpty(ST* pst)
{return pst->top==0;
}//销毁栈
void STDestroy(ST* pst)
{assert(pst);free(pst->a);pst->a=NULL;pst->top=0;pst->capacity=0;}
二、我的队列结构定义
//我的队列
typedef struct {ST s1;ST s2;
} MyQueue;
三、我的队列创建及其初始化
//我的队列的创建及其初始化
MyQueue* myQueueCreate() {MyQueue* myqueue=(MyQueue*)malloc(sizeof(MyQueue));if(myqueue==NULL){perror("malloc fail");exit(-1);}STInit(&myqueue->s1);STInit(&myqueue->s2);return myqueue;
}
四、我的队列入队
//我的队列入队
void myQueuePush(MyQueue* obj, int x) {STPush(&obj->s1,x);
}
五、我的队列出队
//我的队列出队
int myQueuePop(MyQueue* obj) {while(obj->s1.top>1){STPush(&obj->s2,STTop(&obj->s1));STPop(&obj->s1);}int tmp=STTop(&obj->s1);STPop(&obj->s1);while(obj->s2.top>0){STPush(&obj->s1,STTop(&obj->s2));STPop(&obj->s2);}return tmp;
}
六、我的队列取队头元素
//我的队列取队头元素
int myQueuePeek(MyQueue* obj) {while(obj->s1.top>1){STPush(&obj->s2,STTop(&obj->s1));STPop(&obj->s1);}int tmp=STTop(&obj->s1);while(obj->s2.top>0){STPush(&obj->s1,STTop(&obj->s2));STPop(&obj->s2);}return tmp;
}
七、我的队列判空
//我的队列判空
bool myQueueEmpty(MyQueue* obj) {return STEmpty(&obj->s1);
}
八、我的队列销毁
//我的队列销毁
void myQueueFree(MyQueue* obj) {STDestroy(&obj->s1);STDestroy(&obj->s2);free(obj);obj=NULL;
}