其他分享
首页 > 其他分享> > 剑指offer_09 用两个栈实现队列

剑指offer_09 用两个栈实现队列

作者:互联网

 //思路在剑指offer书的图里,很容易理解。这里由于c没有API,所以要先定义Stack结构体,不像JavaScript有已经定义好的结构体。并且一些如弹入弹出的操作,也需要自己定义。
1 typedef struct { 2 int* stk; 3 int stkSize; 4 int stkCapacity; 5 } Stack; 6 7 Stack* stackCreate(int cpacity) { 8 Stack* ret = malloc(sizeof(Stack)); 9 ret->stk = malloc(sizeof(int) * cpacity); 10 ret->stkSize = 0; 11 ret->stkCapacity = cpacity; 12 return ret; 13 } 14 15 void stackPush(Stack* obj, int value) { 16 obj->stk[obj->stkSize++] = value; 17 } 18 19 void stackPop(Stack* obj) { 20 obj->stkSize--; 21 } 22 23 int stackTop(Stack* obj) { 24 return obj->stk[obj->stkSize - 1]; 25 } 26 27 bool stackEmpty(Stack* obj) { 28 return obj->stkSize == 0; 29 } 30 31 void stackFree(Stack* obj) { 32 free(obj->stk); 33 } 34 35 typedef struct { 36 Stack* inStack; 37 Stack* outStack; 38 } CQueue; 39 40 CQueue* cQueueCreate() { 41 CQueue* ret = malloc(sizeof(CQueue)); 42 ret->inStack = stackCreate(10000); 43 ret->outStack = stackCreate(10000); 44 return ret; 45 } 46 47 void in2out(CQueue* obj) { 48 while (!stackEmpty(obj->inStack)) { 49 stackPush(obj->outStack, stackTop(obj->inStack)); 50 stackPop(obj->inStack); 51 } 52 } 53 54 void cQueueAppendTail(CQueue* obj, int value) { 55 stackPush(obj->inStack, value); 56 } 57 58 int cQueueDeleteHead(CQueue* obj) { 59 if (stackEmpty(obj->outStack)) { 60 if (stackEmpty(obj->inStack)) { 61 return -1; 62 } 63 in2out(obj); 64 } 65 int x = stackTop(obj->outStack); 66 stackPop(obj->outStack); 67 return x; 68 } 69 70 void cQueueFree(CQueue* obj) { 71 stackFree(obj->inStack); 72 stackFree(obj->outStack); 73 }

 

标签:obj,offer,队列,CQueue,09,ret,int,inStack,Stack
来源: https://www.cnblogs.com/YoungP7/p/16103628.html