博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
100-2
阅读量:7092 次
发布时间:2019-06-28

本文共 1979 字,大约阅读时间需要 6 分钟。

hot3.png

创建一个带获取最小元素的功能的栈,要求push,pop,getMin的时间复杂度均为O(1)。StackWithMin.h/* * StackWithMin.h * *  Created on: 2012-10-8 *      Author: dapengking */#ifndef STACKWITHMIN_H_#define STACKWITHMIN_H_#include 
using namespace std;template
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 StackWithMin{private: node
*head;public: StackWithMin(); ~StackWithMin(); int isEmpty(); void push(T x); T pop(); T getMin();};template
StackWithMin
::StackWithMin(){ head = new node
((T)0,0); head->min = 0;}template
StackWithMin
::~StackWithMin(){ delete(head); head = 0;}template
int StackWithMin
::isEmpty(){ return head->next == 0;}template
void StackWithMin
::push(T x){ node
*pNewNode = new node
(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
T StackWithMin
::pop(){ T v = head->next->item; node
*p = head->next; head->next = p->next; delete(p); return v;}template
T StackWithMin
::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 
#include "StackWithMin.h"using namespace std;int main() { StackWithMin
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;}

转载于:https://my.oschina.net/dapengking/blog/82038

你可能感兴趣的文章
flutter安装开发环境-问题记录
查看>>
渲染机制/页面性能/错误监控
查看>>
前端构建_webpack
查看>>
程序员如何优雅的记录笔记(同步云端,图床,多端发布)
查看>>
游戏开发者福音:微软开源部分 Minecraft 的 Java 代码
查看>>
leaflet实用插件整理
查看>>
vue基础
查看>>
.NET快速信息化系统开发框架 V3.2-Web版本“产品管理”事例编辑界面新增KindEditor复文本编辑控件...
查看>>
2- OpenCV+TensorFlow 入门人工智能图像处理-opencv入门
查看>>
django模板详解(二)
查看>>
jQuery实现还能输入N字符
查看>>
HTTPS部署笔记
查看>>
ZeroMQ(java)之Router/Dealer模式
查看>>
TCP/IP协议碎碎念
查看>>
Rss订阅
查看>>
Mac - gdb配置
查看>>
ART世界探险(16) - 快速编译器下的方法编译
查看>>
ubuntu安装经典的Gnome桌面
查看>>
Nginx unknown directive "xxxx" 错误解决办法
查看>>
Windows下查看文件MD5值
查看>>