Stack that Support Push, Pop, and GetMin in Constant Time

Design a stack that supports push, pop, and retrieving the minimum element in constant time. Can you do this?

Solution:

struct Node
{
	int min;
	int val;
	Node( int val) {this->min = val; this->val = val;}
};

class stackNode : public stack<Node>
{
public:
	void push(Node& sN);
	void pop();
	int getMin();
	
};
void stackNode::push(Node& sN)
{
	if(this->empty())
	{
		stack<Node>::push(sN);
	}
	else
	{
		if(sN.val < this->top().min) 
			sN.min = sN.val ;
		else 
			sN.min = this->top().min;
		stack<Node>::push(sN);
	}

}
void stackNode::pop()
{
	stack<Node>::pop();
}
int stackNode::getMin()
{
	return this->top().min;
}
int _tmain(int argc, _TCHAR* argv[])
{
	stackNode s_m;
	s_m.push(Node(1));
	s_m.push(Node(2));
	s_m.push(Node(3));
	cout << s_m.getMin() << endl;
	return 0;
}

 Idea: (1) create node which hold the min value 

    (2) creat class inherit the stack hold the node elements, which makes the inherited class be able to hold the created node structure

           (3) override the functions at parent class with push, pop, and getMin, the min of the top of the stack hold the min value of the whole stack

 

posted @ 2013-07-25 07:30  pgu2  阅读(327)  评论(0)    收藏  举报