C++实现包含getMin函数的栈

#include<iostream>
#include<stack>
using namespace std; 
class Solution{
public:
	stack<int> data;//数据栈
	stack<int> mins;//最小值栈
	int top() {
		return data.top();//返回数据栈栈顶
	}
	int getMin() {
		return mins.top();//返回最小值栈栈顶
	}
	void push(int x) {
		data.push(x);
		if (!mins.empty() && x > mins.top()) {
			x = mins.top();
		}//假设我传入数据3,如何最小值栈顶为-8
		//3>-8,那么就拿-8放入最小值栈作为栈顶
		mins.push(x);
	}
	void pop() {
		data.pop();
		mins.pop();
	}
};
int main() {
	Solution s;
	s.push(-3);
	cout << s.getMin() << endl;
	s.push(6);
	cout << s.getMin() << endl;
	s.push(-8);
	cout << s.getMin() << endl;
	s.push(9);
	cout << s.getMin() << endl;
	return 0;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
travel Algrithm. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <malloc.h> #include <conio.h> struct Path { char pass[25]; //sign passed note. int min_distance; //minmax distance from concurrent note.// int nextcity; //next note from current note. struct Path *next; }; int C[25][25]; int Getmin(struct Path *G[25][25],int i,int num_S,char S[25]); // search G[i][n] linking-node. void Write(int i,int n,char S[25],struct Path *G[25][25],int num_S); // Calculate G[i][num_S] void Travel(int size,int i,int n,char S[25],struct Path *G[25][25],int num_S); // signed V-S node. void Trip(int n,char S[25],struct Path *G[25][25]); // Calculate and output the min_distance. void Printpath(char S[],int path[],struct Path *G[][25],int n); // print the path // S[] is the charater of the node. void main() { int n,i,j; int output[25]; char S[25]; struct Path *G[25][25]; printf("Please enter the number of cities:\n"); // Input the numbers of node scanf("%d",&n); printf("Please enter the matrix:\n"); // Input the maxtric of weight. for(i=0;i<n;i++) for(j=0;j<n;j++) scanf("%d",&C[i][j]); printf("The number of cities is:%d\n",n); for(i=0;i<n;i++) { for(j=0;j<n;j++) printf("%d\t",C[i][j]); printf("\n"); } for(i=0;i<n;i++) S[i]='0'; S[i]='\0'; for(i=0;i<n;i++) { G[i][0]=(struct Path *)malloc(sizeof(struct Path)); strcpy(G[i][0]->pass,S); G[i][0]->min_distance=C[i][0]; G[i][0]->next=NULL; } for(i=0;i<n;i++) for(j=1;j<n;j++) G[i][j]=NULL; Trip(n,S,G); Printpath(S,output,G,n); printf("For the demonstration route:\n"); for(i=0;i<n;i++) printf("%d->",output[i]+1); printf("1\n"); getch(); }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值