forked from ppsirker/dsalgo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueueMinUsingStack.java
More file actions
41 lines (35 loc) · 944 Bytes
/
QueueMinUsingStack.java
File metadata and controls
41 lines (35 loc) · 944 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
For problem and solution description please visit the link below
http://www.dsalgo.com/2013/02/QueueMinUsingStackMin.php.html
*/
package com.dsalgo;
/*
* Implement a queue in which push_rear(), pop_front() and get_min() are all constant time operations.
*
* first solution using two stacks
*/
public class QueueMinUsingStack
{
static StackMinimum stackMinimum1=new StackMinimum();
static StackMinimum stackMinimum2=new StackMinimum();
public static void enqueue(int a)
{
stackMinimum1.push(a);
}
public static int dequeue()
{
if(stackMinimum2.size()==0)
{
while(stackMinimum1.size()!=0)
stackMinimum2.push(stackMinimum1.pop());
}
return stackMinimum2.pop();
}
public int getMinimum()
{
return Math.min(
stackMinimum1.size()==0?Integer.MAX_VALUE:stackMinimum1.getMinimum(),
stackMinimum2.size()==0?Integer.MAX_VALUE:stackMinimum2.getMinimum()
);
}
}