Flashcards
Queue from Stack
Flashcards do conjunto (1)
- 1Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of queue. pop() -- Removes the element from in front of queue. peek() -- Get the front element. empty() -- Return whether the queue is empty.class MyQueue {
/** Initialize your data structure here. */
Stack s1;
Stack s2;
public MyQueue() {
s1 = new Stack<>();
s2 = new Stack<>();
}
public void transfer(){
while(!s1.isEmpty()){
s2.push(s1.pop());
}
}
/** Push element x to the back of queue. */
public void push(int x) {
s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(s2.isEmpty()){
transfer();
}
return s2.pop();
}
/** Get the front element. */
public int peek() {
if(s2.isEmpty()){
transfer();
}
return s2.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return s1.isEmpty() && s2.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj
Informações
- Descrição
- FlashCards sobre Queue from Stack, criado por Suhas S em 13-05-2018.
- Criado por
- Suhas S
- Visualizações
- 0
- Avaliação