C++栈和递归

C++栈和递归,第1张

C++栈和递归 一、栈 1.介绍





2.总结

3.应用








#include
#include
#include
using namespace std;
int main(){
	int n;
	cin >> n;
	vector a(n);
	for(int i=0;i>a[i];  // 5 6 4 1 3 2
	}
	
	
   //n个数的入栈顺序:1、2、3、4、5.。。n
   //                 5 6 4 1 3 2 
	stacks;
	int cur=1;
	bool f=1;

	for(int i=0;i< n;i++){
		while( ( s.empty() || s.top()!=a[i] ) && cur <= n)
		{
			s.push(cur);
			cur++;
		}
		if(s.empty() || s.top()!=a[i] ){
			f=0;
			break;
		}else{
			s.pop();
		}
		
	} 
	if(f){
		cout<<"legal"< 
二、递归 
1.阶乘 



2.斐波那契

3.递归函数

#include
using namespace std;
long long f(int x){
	if(x<=0){
		return 0;
	}
	if(x ==1){
		return 1;
	}
	if( x>1 && x % 2 == 0){
		return 3 * f( x / 2) - 1;
	}
	if(x > 1 && x % 2 == 1 ){
		return 3*f( (x+1) / 2 ) -1 ;
	}
}

int main(){
	int x;
	scanf("%d",&x);
	printf("%lldn",f(x));
} 
4.汉诺塔









#include
#include
using namespace std;
stack s[3];//定义三个栈 

void move(int x,int y){
	int temp=s[x].top();
	s[x].pop();
	s[y].push(temp); 
	cout<< x<<"-->"<>n;
	for(int i=n;i>=1;i--){
		s[0].push(i);
	}
	hanoi(0,1,2,n);
	while(!s[2].empty())
    {
    	cout< 
5.汉诺塔升级 


#include
#include
using namespace std;
long long f[65],g[65];
stack s[3];


int main()
{
	int n;
	cin>>n;
	f[1]=1;
	for(int i=2;i<=n;i++){
	    f[i]= 2* f[i-1] + 1;	
	}
	g[1]=1;
	for(int i=2;i<=n;i++){
		g[i]= 2* g[i-1] + i;
	}
	cout<

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5714505.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-17
下一篇2022-12-17

发表评论

登录后才能评论

评论列表(0条)

    保存