C++数据结构 栈

1.翻转字符串(hdu 1062)

#include <bits/stdc++.h>
using namespace std;
int main(){
	int n;
	char c;
	scanf("%d",&n);
	getchar();
	while(n--){
		stack<char> s;
		while(true){
			c = getchar();
			if(c==' '||c==EOF||c=='\n'){
				while(!s.empty()){
					cout<<s.top();
					s.pop();
				}
				if(c=='\n'||c == EOF) break;
				else cout<<' ';
			}
			else{
				s.push(c);
			}
		}
		cout<<endl;
	}
	return 0;
}

2.P2947

#include <bits/stdc++.h>
using namespace std;
int n,x;
stack<int> s;
int main(){
	scanf("%d",&n);
	int h[n+1],ans[n+1];//不这么写洛谷会显示空间不足 
	for (int i = 1;i<=n;i++){
		scanf("%d",&x);
		h[i]=x;
	}
	for (int i = n;i>=1;i--){
		while(!s.empty()&&h[s.top()]<=h[i]){
			s.pop();
		}
		if(s.empty()) ans[i]=0;
		else ans[i]=s.top();
		s.push(i);
	}
	for (int i = 1;i<=n;i++) printf("%d\n",ans[i]);
	printf("\n");
	return 0;
}

3.P5788

#include <bits/stdc++.h>
using namespace std;
int n;
int main(){
	scanf("%d",&n);
	int a[n+1],b[n+1];
	stack<int> s;
	for (int i = 0;i<=n;i++) a[i]=0,b[i]=0;
	for(int i = 1;i<=n;i++) scanf("%d",&a[i]);
	for (int i=n;i>=1;i--){
		while(!s.empty()&&a[s.top()]<=a[i]) s.pop();
		if (s.empty()) b[i]=0;
		else b[i] = s.top();
		s.push(i);
	}
	for (int i = 1;i<=n;i++) printf("%d ",b[i]);
	printf("\n");
	return 0;
}

4.P1449后缀表达式(题意理解起来很累)

#include <bits/stdc++.h>
using namespace std;
int zh(char x){//将字符转换为数字
	int a =0;
	a=int(x)-48;
	return a;
}
int sum[100000];
int Ayaka(int x){//将一堆一位数转换为多位数
	int a =0;
	for (int i=0;i<x;i++) a+=sum[i]*pow(10,x-i-1);
	return a;
}
int count(int x,char c,int y){
	int a=0;
	switch (c){
		case '+': 
			a = x+y;
			break;
		case '-': 
			a = x-y;
			break;
		case '*': 
			a = x*y;
			break;
		case '/': 
			a = x/y;
			break;
		default: 
			break;
	}
	return a;
}
stack<int> s;
int main(){
	string st;
	cin>>st;
	int j=0,i=0;
	while(st[i]!='@'){
		if(isdigit(st[i])) {
			sum[j]=zh(st[i]);
			j++;
		}
		else if(st[i]=='.'){
			int t = Ayaka(j);
			s.push(t);
			j = 0;
		}
		else if(st[i]=='+'||st[i]=='-'||st[i]=='*'||st[i]=='/'){
			int na=s.top();
			s.pop();
			int nb = s.top();
			s.pop();
			int k=count(nb,st[i],na);
			s.push(k);
		}
		i++;
	}
	cout<<s.top()<<endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值