C语言解题代码如下:
typedef int QDataType; typedef struct QueueNode { struct QueueNode* next; QDataType data; }QueueNode; typedef struct Queue { QueueNode* phead; QueueNode* ptail; }Queue; bool QueueEmpty(Queue* pq) { assert(pq); return pq->ptail == NULL && pq->phead == NULL; } void QueueInit(Queue* pq) { assert(pq); pq->phead = pq->ptail = NULL; } void QueueDestory(Queue* pq) { assert(pq); QueueNode* cur = pq->phead; while (cur) { QueueNode* next = cur->next; free(cur); cur = next; } pq->phead = pq->ptail = NULL; } void QueuePush(Queue* pq, QDataType x) { assert(pq); QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode)); if (newnode == NULL) { printf("malloc fail\n"); exit(-1); } newnode->data = x; newnode->next = NULL; if (pq->ptail == NULL) { pq->phead = pq->ptail = newnode; } else { pq->ptail->next = newnode; pq->ptail = newnode; } } void QueuePop(Queue* pq) { assert(pq); if (pq->phead->next == NULL) { free(pq->phead); pq->phead = pq->ptail = NULL; } else { QueueNode* next = pq->phead->next; free(pq->phead); pq->phead = next; } } int QueueSize(Queue* pq) { assert(pq); int n = 0; QueueNode* cur = pq->phead; while (cur) { n++; cur = cur->next; } return n; } QDataType QueueFront(Queue* pq) { assert(pq); assert(!QueueEmpty(pq)); return pq->phead->data; } QDataType QueueBack(Queue* pq) { assert(pq); assert(!QueueEmpty(pq)); return pq->ptail->data; } typedef struct { Queue q1; Queue q2; } MyStack; MyStack* myStackCreate() { MyStack* pst=(MyStack*)malloc(sizeof(MyStack)); QueueInit(&pst->q1); QueueInit(&pst->q2); return pst; } void myStackPush(MyStack* obj, int x) { assert(obj); if(!QueueEmpty(&obj->q1)) { QueuePush(&obj->q1,x); } else { QueuePush(&obj->q2,x); } } int myStackPop(MyStack* obj) { assert(obj); Queue * emptyq=&obj->q1; Queue * noemptyq=&obj->q2; if(!QueueEmpty(&obj->q1)) { emptyq=&obj->q2; noemptyq=&obj->q1; } //将非空队列中的size-1个导入空队列 while(QueueSize(noemptyq)>1) { QueuePush(emptyq,QueueFront(noemptyq)); QueuePop(noemptyq);//去除 } int top=QueueFront(noemptyq); QueuePop(noemptyq); return top; } int myStackTop(MyStack* obj) { if(!QueueEmpty(&obj->q1)) { return QueueBack(&obj->q1); } else { return QueueBack(&obj->q2); } } bool myStackEmpty(MyStack* obj) { assert(obj); return QueueEmpty(&obj->q1)&&QueueEmpty(&obj->q2); } void myStackFree(MyStack* obj) { assert(obj); QueueDestory(&obj->q1); QueueDestory(&obj->q2); free(obj); }