Amazon Interview Question
SDE-2sCountry: United States
class Deque
{
Stack<Integer> primary = new Stack<>();
Stack<Integer> secondary = new Stack<>();
public void addRight(int item)
{
primary.push(item);
}
public int popRight()
{
int item=primary.peek();
primary.pop();
return item;
}
public void addLeft(int item)
{
while(!primary.empty()) {
secondary.push(primary.peek());
primary.pop();
}
secondary.push(item);
while(!secondary.empty())
{
primary.add(secondary.peek());
secondary.pop();
}
}
public int popLeft()
{
while(!primary.empty()) {
secondary.push(primary.peek());
primary.pop();
}
int item=secondary.peek();
secondary.pop();
while(!secondary.empty())
{
primary.add(secondary.peek());
secondary.pop();
}
return item;
}
}
- Manasa August 09, 2020