AcWing 20. 用两个栈实现队列 C语言代码
原题链接
简单
作者:
123_14
,
2021-04-26 15:19:24
,
所有人可见
,
阅读 562
C语言 代码
typedef struct {
int Ldata[100010];
int Ltop;
int Rdata[100010];
int Rtop;
} MyQueue;
//初始化这里的maxSize不知道怎么用,只好开两个大数组了
/** Initialize your data structure here. */
MyQueue* myQueueCreate(int maxSize) {
MyQueue * p = malloc(sizeof(MyQueue));
p->Ltop = -1; p->Rtop = -1;
return p;
}
/** Push element x to the back of queue. */
void myQueuePush(MyQueue* obj, int x) {
obj->Ltop++;
obj->Ldata[obj->Ltop] = x;
}
/** Removes the element from in front of queue and returns that element. */
int myQueuePop(MyQueue* obj) {
while (obj->Ltop > 0) {
obj->Rdata[++obj->Rtop] = obj->Ldata[obj->Ltop--];
}
int res = obj->Ldata[obj->Ltop];
obj->Ltop = -1;
while (obj->Rtop > -1) {
obj->Ldata[++obj->Ltop] = obj->Rdata[obj->Rtop--];
}
return res;
}
/** Get the front element. */
int myQueuePeek(MyQueue* obj) {
return obj->Ldata[0];
}
/** Returns whether the queue is empty. */
bool myQueueEmpty(MyQueue* obj) {
if (obj->Ltop == -1) return true;
return false;
}
void myQueueFree(MyQueue* obj) {
free(obj);
}
/**
* Your MyQueue struct will be instantiated and called as such:
* struct MyQueue* obj = myQueueCreate(maxSize);
* myQueuePush(obj, x);
* int param_2 = myQueuePop(obj);
* int param_3 = myQueuePeek(obj);
* bool param_4 = myQueueEmpty(obj);
* myQueueFree(obj);
*/
//补充,后来知道怎么用maxSize了
typedef struct {
int * Ldata;
int Ltop;
int * Rdata;
int Rtop;
} MyQueue;
/** Initialize your data structure here. */
MyQueue* myQueueCreate(int maxSize) {
MyQueue * p = malloc(sizeof(MyQueue));
//注意这里
p->Ldata = malloc(sizeof(int) * maxSize); p->Rdata = malloc(sizeof(int) * maxSize);
p->Ltop = -1; p->Rtop = -1;
return p;
}
/** Push element x to the back of queue. */
void myQueuePush(MyQueue* obj, int x) {
obj->Ltop++;
obj->Ldata[obj->Ltop] = x;
}
/** Removes the element from in front of queue and returns that element. */
int myQueuePop(MyQueue* obj) {
while (obj->Ltop > 0) {
obj->Rdata[++obj->Rtop] = obj->Ldata[obj->Ltop--];
}
int res = obj->Ldata[obj->Ltop];
obj->Ltop = -1;
while (obj->Rtop > -1) {
obj->Ldata[++obj->Ltop] = obj->Rdata[obj->Rtop--];
}
return res;
}
/** Get the front element. */
int myQueuePeek(MyQueue* obj) {
return obj->Ldata[0];
}
/** Returns whether the queue is empty. */
bool myQueueEmpty(MyQueue* obj) {
if (obj->Ltop == -1) return true;
return false;
}
void myQueueFree(MyQueue* obj) {
free(obj);
}
/**
* Your MyQueue struct will be instantiated and called as such:
* struct MyQueue* obj = myQueueCreate(maxSize);
* myQueuePush(obj, x);
* int param_2 = myQueuePop(obj);
* int param_3 = myQueuePeek(obj);
* bool param_4 = myQueueEmpty(obj);
* myQueueFree(obj);
*/