Skip to content

Commit 62b0c68

Browse files
Merge pull request youngyangyang04#913 from KingArthur0205/remote
添加 0232.用栈实现队列.md C语言版本
2 parents c494b18 + e6f059f commit 62b0c68

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

problems/0232.用栈实现队列.md

+77
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,83 @@ MyQueue.prototype.empty = function() {
349349
};
350350
```
351351

352+
C:
353+
```C
354+
/*
355+
1.两个type为int的数组(栈),大小为100
356+
第一个栈stackIn用来存放数据,第二个栈stackOut作为辅助用来输出数据
357+
2.两个指针stackInTop和stackOutTop,分别指向栈顶
358+
*/
359+
typedef struct {
360+
int stackInTop, stackOutTop;
361+
int stackIn[100], stackOut[100];
362+
} MyQueue;
363+
364+
/*
365+
1.开辟一个队列的大小空间
366+
2.将指针stackInTop和stackOutTop初始化为0
367+
3.返回开辟的队列
368+
*/
369+
MyQueue* myQueueCreate() {
370+
MyQueue* queue = (MyQueue*)malloc(sizeof(MyQueue));
371+
queue->stackInTop = 0;
372+
queue->stackOutTop = 0;
373+
return queue;
374+
}
375+
376+
/*
377+
将元素存入第一个栈中,存入后栈顶指针+1
378+
*/
379+
void myQueuePush(MyQueue* obj, int x) {
380+
obj->stackIn[(obj->stackInTop)++] = x;
381+
}
382+
383+
/*
384+
1.若输出栈为空且当第一个栈中有元素(stackInTop>0时),将第一个栈中元素复制到第二个栈中(stack2[stackTop2++] = stack1[--stackTop1])
385+
2.将栈顶元素保存
386+
3.当stackTop2>0时,将第二个栈中元素复制到第一个栈中(stack1[stackTop1++] = stack2[--stackTop2])
387+
*/
388+
int myQueuePop(MyQueue* obj) {
389+
//优化:复制栈顶指针,减少对内存的访问次数
390+
int stackInTop = obj->stackInTop;
391+
int stackOutTop = obj->stackOutTop;
392+
//若输出栈为空
393+
if(stackOutTop == 0) {
394+
//将第一个栈中元素复制到第二个栈中
395+
while(stackInTop > 0) {
396+
obj->stackOut[stackOutTop++] = obj->stackIn[--stackInTop];
397+
}
398+
}
399+
//将第二个栈中栈顶元素(队列的第一个元素)出栈,并保存
400+
int top = obj->stackOut[--stackOutTop];
401+
//将输出栈中元素放回输入栈中
402+
while(stackOutTop > 0) {
403+
obj->stackIn[stackInTop++] = obj->stackOut[--stackOutTop];
404+
}
405+
//更新栈顶指针
406+
obj->stackInTop = stackInTop;
407+
obj->stackOutTop = stackOutTop;
408+
//返回队列中第一个元素
409+
return top;
410+
}
411+
412+
//返回输入栈中的栈底元素
413+
int myQueuePeek(MyQueue* obj) {
414+
return obj->stackIn[0];
415+
}
416+
417+
//若栈顶指针均为0,则代表队列为空
418+
bool myQueueEmpty(MyQueue* obj) {
419+
return obj->stackInTop == 0 && obj->stackOutTop == 0;
420+
}
421+
422+
//将栈顶指针置0
423+
void myQueueFree(MyQueue* obj) {
424+
obj->stackInTop = 0;
425+
obj->stackOutTop = 0;
426+
}
427+
```
428+
352429
353430
-----------------------
354431
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
 (0)