225 Implement Stack using Queues
OA:
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.offer(x); int k = queue.size() - 1; while(k > 0) { queue.offer(queue.poll()); k--; } } /** Removes the element on top of the stack and returns that element. */ public int pop() { return queue.poll(); } /** Get the top element. */ public int top() { return queue.peek(); } /** Returns whether the stack is empty. */ public boolean empty() { return queue.isEmpty(); } }
oa是push一次就逆序排一次(相当于每次push一个之后都把新push进去的那个排到最前面,这样下次pop的时候就是pop的这一个。)
ma在top和pop的时候才把最后一个调到前面来,而且每次都要重新排。(感觉其实差不多,要看这个这个stack是pop和top用得多还是push用得多)
MA:
class MyStack { ArrayDeque<Integer> q1=new ArrayDeque<Integer>(); /** Initialize your data structure here. */ public MyStack() { } /** Push element x onto stack. */ public void push(int x) { q1.add(x); } /** Removes the element on top of the stack and returns that element. */ public int pop() { for(int i=0;i<q1.size()-1;i++){ q1.add(q1.remove()); } return q1.remove(); } /** Get the top element. */ public int top() { for(int i=0;i<q1.size()-1;i++){ q1.add(q1.remove()); } int temp = q1.element(); q1.add(q1.remove()); return temp; } /** Returns whether the stack is empty. */ public boolean empty() { return q1.isEmpty(); } }
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.offer(x); int k = queue.size() - 1; while(k > 0) { queue.offer(queue.poll()); k--; } } /** Removes the element on top of the stack and returns that element. */ public int pop() { return queue.poll(); } /** Get the top element. */ public int top() { return queue.peek(); } /** Returns whether the stack is empty. */ public boolean empty() { return queue.isEmpty(); } }
oa是push一次就逆序排一次(相当于每次push一个之后都把新push进去的那个排到最前面,这样下次pop的时候就是pop的这一个。)
ma在top和pop的时候才把最后一个调到前面来,而且每次都要重新排。(感觉其实差不多,要看这个这个stack是pop和top用得多还是push用得多)
MA:
class MyStack { ArrayDeque<Integer> q1=new ArrayDeque<Integer>(); /** Initialize your data structure here. */ public MyStack() { } /** Push element x onto stack. */ public void push(int x) { q1.add(x); } /** Removes the element on top of the stack and returns that element. */ public int pop() { for(int i=0;i<q1.size()-1;i++){ q1.add(q1.remove()); } return q1.remove(); } /** Get the top element. */ public int top() { for(int i=0;i<q1.size()-1;i++){ q1.add(q1.remove()); } int temp = q1.element(); q1.add(q1.remove()); return temp; } /** Returns whether the stack is empty. */ public boolean empty() { return q1.isEmpty(); } }
评论
发表评论