classMyStack { Queue<Integer> q; /** Initialize your data structure here. */ publicMyStack() { q = newLinkedList<>(); }
/** Push element x onto stack. */ publicvoidpush(int x) { q.offer(x); }
/** Removes the element on top of the stack and returns that element. */ publicintpop() { for (inti=1; i < q.size(); i++){ q.offer(q.poll()); } return q.poll(); }
/** Get the top element. */ publicinttop() { for (inti=1; i < q.size(); i++){ q.offer(q.poll()); } inttop= q.peek(); q.offer(q.poll()); return top; }
/** Returns whether the stack is empty. */ publicbooleanempty() { return q.isEmpty(); } }
下面是相似的Java代码,请关注两者的区别:
classMyStack {
Queue<Integer> q; /** Initialize your data structure here. */ publicMyStack() { q = newLinkedList<>(); }
/** Push element x onto stack. */ publicvoidpush(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. */ publicvoidpop() { queue.remove(); }
/** Get the top element. */ publicinttop() { return queue.peek(); }
/** Returns whether the stack is empty. */ publicbooleanempty() { return queue.isEmpty(); } }
下面是Python的代码:
classMyStack:
def__init__(self): """ Initialize your data structure here. """ self.queue = []
defpush(self, x: int) -> None: """ Push element x onto stack. """ self.queue.append(x)
defpop(self) -> int: """ Removes the element on top of the stack and returns that element. """ return self.queue.pop()
deftop(self) -> int: """ Get the top element. """ return self.queue[-1]
defempty(self) -> bool: """ Returns whether the stack is empty. """ return self.queue == []