100-2

创建一个带获取最小元素的功能的栈,要求push,pop,getMin的时间复杂度均为O(1)。

StackWithMin.h

/*
 * StackWithMin.h
 *
 *  Created on: 2012-10-8
 *      Author: dapengking
 */

#ifndef STACKWITHMIN_H_
#define STACKWITHMIN_H_

#include <iostream>

using namespace std;
template <class T>
class node{
public:
	T item;
	node *min;
	node *next;

	node(T x,node *p){
		item = x;
		min = 0;
		next = p;
	}

	void setMin(node *pMin){
		min = pMin;
	}
};

template <class T>
class StackWithMin{
private:
	node<T> *head;

public:
	StackWithMin();
	~StackWithMin();
	int isEmpty();
	void push(T x);
	T pop();
	T getMin();
};

template <class T>
StackWithMin<T>::StackWithMin(){
	head = new node<T>((T)0,0);
	head->min = 0;
}

template <class T>
StackWithMin<T>::~StackWithMin(){
	delete(head);
	head = 0;
}

template <class T>
int StackWithMin<T>::isEmpty(){
	return head->next == 0;
}

template <class T>
void StackWithMin<T>::push(T x){
	node<T> *pNewNode = new node<T>(x,head->next);
	if(head->next != 0){
		if(x <= head->next->min->item){
			pNewNode->min = pNewNode;
		}else{
			pNewNode->min = head->next->min;
		}
	}else{
		pNewNode->min = pNewNode;
	}
	head->next = pNewNode;
}

template <class T>
T StackWithMin<T>::pop(){
	T v = head->next->item;
	node<T> *p = head->next;
	head->next = p->next;
	delete(p);
	return v;
}

template <class T>
T StackWithMin<T>::getMin(){
	T min;
	if(head->next != 0){
		min = head->next->min->item;
	}
	return min;
}

#endif /* STACKWITHMIN_H_ */

100-2.cpp

//============================================================================
// Name        : 100-2.cpp
// Author      : dapengking
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include "StackWithMin.h"

using namespace std;

int main() {
	StackWithMin<int> s;
	s.push(100);
	s.push(15);
	s.push(2);
	s.push(30);
	while(!s.isEmpty()){
		cout << "min:" << s.getMin() << endl;
		cout << s.pop() << " ";
	}
	cout << endl;
	return 0;
}

你可能感兴趣的:(100-2)