【数据结构】栈的应用-栈与递归

求n个整数的乘积:

给定n个整数储存在数组里,利用递归来实现求乘积。

#include<stdio.h>
int productArray(int a[],int n){
    if(n<1){
        return 1;
    }
    return productArray(a,n-1)*a[n];
}
int main()
{
    int a[]={0,-1,2,3,4,5,6};
    int n=6;
    int ans=productArray(a,n);
    return 0*printf("%d\n",ans);
}

对于给定一组有序的整数,采用折半查找法查找整数x是否存在。

利用二分来实现查找。

#include<stdio.h>
int Binary_Search(int a[],int low,int high,int x){
    int mid;
    if(low<=high){
        mid=(low+high)>>1;
        if(x==a[mid]){
            return mid;
        }else if(x<a[mid]){
            return Binary_Search(a,low,mid-1,x);
        }else{
            return Binary_Search(a,mid+1,high,x);
        }
    }
    return -1;
}
int main()
{
    int a[6]={1,2,3,5,6,8},t;
    for(int i=1;i<=8;i++){
        t=Binary_Search(a,0,6,i);
        if(t==-1){
            printf("Not found %d !!!\n",i);
        }else{
            printf("Found %d !!! Locate in %d\n",i,t);
        }
    }
    return 0;
}

求n个元素组成的集合,输出该集合的全排列

#include<stdio.h>
template<class T>
void Swap(T &a,T &b){
    T   temp=a;
        a=b;
        b=temp;
}
void Perm(char List[],int step,int n){
    if(step==n-1){
        for(int i=0;i<n;i++){
            printf("%c",List[i]);
        }puts("");
        return ;
    }else{
        for(int i=step;i<n;i++){
            Swap(List[step],List[i]);
            Perm(List,step+1,n);
            Swap(List[step],List[i]);
        }
    }
}
int main()
{
    char List[]="abc";
    Perm(List,0,3);
}

n阶 Hanoi  问题:

#include<stdio.h>
void Move(int n,char A,char B){
    printf("(%d): %c -> %c\n",n,A,B);
}
void Hanoi(int n,char A,char B,char C){
    if(n==1){
        Move(n,A,C);
    }else{
        Hanoi(n-1,A,C,B);
        Move(n,A,C);
        Hanoi(n-1,B,A,C);
    }
}
int main()
{
    Hanoi(3,'A','B','C');
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Z_sea/article/details/85173557