Created
October 27, 2016 20:07
-
-
Save kartikkukreja/fcb748f29bc044a8076a09c8d9969e63 to your computer and use it in GitHub Desktop.
Queue with min operation using deque
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <typename T> | |
class QueueWithMin { | |
private: | |
queue<T> Q; | |
deque<T> D; | |
public: | |
void enqueue(T& x) { | |
Q.push(x); | |
while (!D.empty() && D.back() > x) | |
D.pop_back(); | |
D.push_back(x); | |
} | |
T dequeue() { | |
if (Q.empty()) | |
throw "queue empty"; | |
if (D.front() == Q.front()) | |
D.pop_front(); | |
T top = Q.front(); Q.pop(); | |
return top; | |
} | |
T getMin() { | |
return D.front(); | |
} | |
int size() { | |
return Q.size(); | |
} | |
bool empty() { | |
return Q.empty(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment