队列是先进先出,栈是先进后出,本题的关键就在于如何用栈实现先进先出。其中一种方法就是利用双栈。此处使用链栈,应该是因为题目没给出具体的栈的大小。而顺序栈必须提前声明栈的大小。理解双栈的方法不难,于我而言,真正麻烦的是对链栈的操作。代码如下:
typedef struct myStack{
int val;
struct mystack*next;
}MyStack;
typedef struct {
MyStack*s1;
int cnt;
} MyQueue;
/** Initialize your data structure here. */
MyQueue* myQueueCreate() {
MyQueueQ=(MyQueue)malloc(sizeof(MyQueue));
memset(Q,0,sizeof(MyQueue));
return Q;
}
/** Push element x to the back of queue. /
void myQueuePush(MyQueue obj, int x) {
MyStackn=(MyStack)malloc(sizeof(MyStack));
MyStack*s2=NULL,*t=NULL;
n->val=x;
n->next=NULL;
while(obj->s1)
{
t=obj->s1;
obj->s1=obj->s1->next;
t->next=s2;
s2=t;
}
obj->s1=n;
while(s2)
{
t=s2;
s2=s2->next;
t->next=obj->s1;
obj->s1=t;
}
obj->cnt++;
}
/** Removes the element from in front of queue and returns that element. /
int myQueuePop(MyQueue obj) {
MyStack*temp=obj->s1;
int num;
obj->s1=obj->s1->next;
obj->cnt–;
num=temp->val;
free(temp);
return num;
}
/** Get the front element. /
int myQueuePeek(MyQueue obj) {
return obj->s1->val;
}
/** Returns whether the queue is empty. /
bool myQueueEmpty(MyQueue obj) {
return !obj->cnt;
}
void myQueueFree(MyQueue* obj) {
MyStack*temp=NULL;
while(obj->s1)
{
temp=obj->s1;
obj->s1=temp->next;
free(temp);
}
free(obj);
}
/**
-
Your MyQueue struct will be instantiated and called as such:
-
MyQueue* obj = myQueueCreate();
-
myQueuePush(obj, x);
-
int param_2 = myQueuePop(obj);
-
int param_3 = myQueuePeek(obj);
-
bool param_4 = myQueueEmpty(obj);
-
myQueueFree(obj);
*/