題目:
定義棧的資料結構,要求添加一個min函數,能夠得到棧的最小元素。
要求函數min、push以及pop的時間複雜度都是O(1)。
C++實現:
輸入格式是:
1 10
2
1 代表push,後面的數字是要push的內容,2代表pop
代碼如下:
#include <iostream>#include <fstream>#include <string>using namespace std;template <class T>class MinStackElement{public: T data; // the data stored T min; // the minimum element under the current element};template <class T>class MinStack{public: MinStack(int max_size); void push(T new_data); T pop(); T minElement();private: MinStackElement<T> *elements; int size; int top;};template <class T>MinStack<T>::MinStack(int max_size){ elements = new MinStackElement<T>[max_size]; size = max_size; top = 0;}template <class T>void MinStack<T>::push(T new_data){ top ++; elements[top - 1].data = new_data; if(top == 1) { elements[top - 1].min = new_data; } else { if(new_data < elements[top - 2].min) { elements[top - 1].min = new_data; } else { elements[top - 1].min = elements[top - 2].min; } }}template <class T>T MinStack<T>::pop(){ if(top == 0) return T(); T value; value = elements[top - 1].data; top --; return value;}template <class T>T MinStack<T>::minElement(){ return elements[top - 1].min;}int main() { ifstream fin ("minstack.in"); ofstream fout ("minstack.out"); int instruction, num; MinStack<int> min_stack(50); if(fin.good() == false) { fout << "file open failed" << endl; return 0; } while(true) { if(fin.eof()) break; fin >> instruction; if(instruction == 1) { fin >> num; min_stack.push(num); fout << "push : " << num << ", the minimum element : " << min_stack.minElement() << endl; } else if(instruction == 2) { num = min_stack.pop(); fout << "pop : " << num << ", the minimum element : " << min_stack.minElement() << endl; } }}
範例輸入:
1 101 41 111 51 81 90221 61 21 3022
範例輸出:
push : 10, the minimum element : 10push : 4, the minimum element : 4push : 11, the minimum element : 4push : 5, the minimum element : 4push : 8, the minimum element : 4push : 90, the minimum element : 4pop : 90, the minimum element : 4pop : 8, the minimum element : 4push : 6, the minimum element : 4push : 2, the minimum element : 2push : 30, the minimum element : 2pop : 30, the minimum element : 2pop : 2, the minimum element : 4