leetcode 225. Implement Stack using Queues

xiaoxiao2021-02-28  131

原题:

Implement the following operations of a stack using queues.

push(x) -- Push element x onto stack.pop() -- Removes the element on top of the stack.top() -- Get the top element.empty() -- Return whether the stack is empty. Notes: You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

Credits: Special thanks to @jianchao.li.fighter for adding this problem and all test cases.

题目的意思就是完成一个完整的栈功能。

代码如下:

typedef struct { int* var; int flag; int maxsize; } MyStack; /** Initialize your data structure here. */ MyStack* myStackCreate(int maxSize) { MyStack* st; st=(struct MyStack*)malloc(sizeof(MyStack)); st->var=(int*)malloc(sizeof(int)*maxSize); st->flag=-1; st->maxsize=maxSize; return st; } /** Push element x onto stack. */ void myStackPush(MyStack* obj, int x) { if(obj->flag+1<obj->maxsize) { obj->flag++; *(obj->var+obj->flag)=x; } } /** Removes the element on top of the stack and returns that element. */ int myStackPop(MyStack* obj) { if(obj->flag-1>-2) { int x=*(obj->var+obj->flag); obj->flag--; return x; } return 0; } /** Get the top element. */ int myStackTop(MyStack* obj) { return *(obj->var+obj->flag); } /** Returns whether the stack is empty. */ bool myStackEmpty(MyStack* obj) { if(obj->flag==-1) return true; return false; } void myStackFree(MyStack* obj) { free(obj->var); }这个还是挺简单的。

转载请注明原文地址: https://www.6miu.com/read-17635.html

最新回复(0)