题解思路 ❤
完全忘了java有自带的函数了
而且完全忽略了题目要求的是队列功能实现栈。
- 用一个队列即可
JAVA代码
class MyStack {
Queue<Integer> queue;
/** Initialize your data structure here. */
public MyStack() {
queue= new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
queue.add(x);
for(int i=1 ; i<queue.size() ; i++)
queue.add(queue.remove());
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue.poll(); //和pop功能相似
}
/** Get the top element. */
public int top() {
return queue.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue.size() == 0 ;
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
C代码
typedef struct {
int top;
int stack[100000];
} MyStack;
/** Initialize your data structure here. */
MyStack* myStackCreate() {
MyStack *s; // 记得新建结构体
s = (MyStack *)malloc(sizeof(MyStack));
s->top = -1;
return s;
}
/** Push element x onto stack. */
void myStackPush(MyStack* obj, int x) {
obj->stack[++obj->top]=x; //是->不是.
}
/** Removes the element on top of the stack and returns that element. */
int myStackPop(MyStack* obj) {
return obj->stack[obj->top--];
}
/** Get the top element. */
int myStackTop(MyStack* obj) {
return obj->stack[obj->top];
}
/** Returns whether the stack is empty. */
bool myStackEmpty(MyStack* obj) {
return obj->top==-1 ? 1 : 0;
}
void myStackFree(MyStack* obj) {
obj->top=-1;
free(obj); // 有一个free
}
/**
* Your MyStack struct will be instantiated and called as such:
* MyStack* obj = myStackCreate();
* myStackPush(obj, x);
* int param_2 = myStackPop(obj);
* int param_3 = myStackTop(obj);
* bool param_4 = myStackEmpty(obj);
* myStackFree(obj);
*/