Reputation:
I'm trying to implement a custom stack that always returns the min element. Effectively thus I'm maintaining two stacks. I've implemented the push method in my custom stack but feel at a bit of a loss implementing the pop. Ideally I'm trying to write a custom overload of for the == operator two compare two nodes. This is my node implementation.
template<typename T> class stack;
template<typename T> class node{
friend class stack<T>;
public:
node():T(NULL),next(NULL){}
node(T data):data(data), next(NULL){}
private:
T data;
node<T>* next;
};
And here's my stack push and pop
void push(T item){
node<T>* N = new node<T>(item);
if(top == nullptr){
top = N;
min_top = N;
++elements;
return;
}
if(item < min_top->data) N->next = min_top;
min_top = N;
N->next = top;
top = N;
++elements;
}
........... ...........
T pop(){
if(top == nullptr)throw std::runtime_error("stack empty");
T item = top->data;
node<T>* P = top;
top = P->next;
delete P;
--elements;
return item;
}
This is the method signature I've defined for the equality overload.
bool operator==(const node<T>& other){
}
The idea is to pop the minimum element(top of the min stack) of the min_stack if it's the same as the top of the main stack.
Upvotes: 0
Views: 211
Reputation: 283803
If you already have operator<
(which you need for a sorted collection of any type), then there's a pattern for correctly defining operator==
:
bool operator==(const node<T>& other) const
{
if (*this < other) return false;
if (other < *this) return false;
return true;
}
Or you can make it even more general using std::less
:
bool operator==(const node<T>& other) const
{
using std::less;
if (less(*this, other)) return false;
if (less(other, *this)) return false;
return true;
}
Upvotes: 1