面试题-Stack的最小值o(1)
2016-01-31 11:16
489 查看
// Stack.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> using namespace std; template <class Type> struct Stack { private: Type *_stack; int _top; int _min; int _size; public: Stack(const Type &size):_size(size),_top(0),_min(0) { _stack = new Type[size];//(Type*)malloc(sizeof()) } void push(const Type &value) { if(_top == 0) { _min = value; } else if(_top == _size) { cout<<"Push failed,the stack is full"<<endl; return; } _stack[_top++] = value-_min; if(value < _min) { _min = value; } } Type pop() { if(_top == 0) { cout<<"Pop failed,the stack is emply."<<endl; return -1; } Type popvalue; if(_stack[--_top]<0) { popvalue = _min; _min = _min-_stack[_top]; } else { popvalue = _min + _stack[_top]; } return popvalue; } Type min() { return _min; } }; int _tmain(int argc, _TCHAR* argv[]) { Stack<int> sk(30); sk.push(8); sk.push(7); sk.push(6); sk.push(5); sk.push(9); sk.push(4); sk.push(3); cout<<sk.min()<<endl;//3 cout<<sk.pop()<<endl;//3 cout<<sk.min()<<endl;//4 cout<<sk.pop()<<endl;//4 cout<<sk.min()<<endl;//5 cout<<sk.pop()<<endl;//9 cout<<sk.min()<<endl;//5 cout<<sk.pop()<<endl;//5 cout<<sk.min()<<endl;//6 cout<<sk.pop()<<endl;//6 cout<<sk.min()<<endl;//7 cout<<sk.pop()<<endl;//7 cout<<sk.min()<<endl;//8 cout<<sk.pop()<<endl;//8 return 0; }
相关文章推荐
- 面试笔试杂项积累-leetcode 46-50
- 面试笔试杂项积累-leetcode 41-45
- 面试笔试杂项积累-leetcode 36-40
- 每一个程序员都是自学成才
- 面试题 -二元查找树转变成排序的双向链表
- 一些面试常见问题
- 黑马程序员——继承
- PHP面试题三
- PHP面试题二
- 黑马程序员——Java多线程
- 面试题总结-阿里神马和通联数据(算法)
- 浮躁程序员的建议
- 面试事
- 黑马程序员-----------class对象的获取方法
- 一个女程序员的年终总结
- 黑马程序员-----------1.30编程所感
- 简悦创始人云风谈程序员的职业素养
- 简悦创始人云风谈程序员的职业素养
- 一道Google面试题目:4个线程写4个文件
- 做程序员的一些励志故事----持续之道(程序员修炼之道)