栈的使用

#include <iostream>
#include "SqStackClass.cpp"
using namespace std;

//有1~n的n个元素,通过一个栈可以产生多种出栈序列,设计一个算法判断
//序列str是否为一个合适的出栈序列,并给出操作过程,要求用相关数据进行
//测试。
template <typename T>
bool isSerial(T str[],int n)
{
    int i,j;T e;
    int a[MaxSize];
    SqStackClass<T> st;//建立一个顺序栈
    for(int i =0;i<n;i++) a[i]=i+1;
    while(i<n && j<n)
    {
        if(st.StackEmpty()||(st.GetTop(e)&& e!=a[i]))//一种是空的,一种是非空空栈,
        //取出栈顶数据,不是当前值。都可以入栈
        {
            st.Push(a[i]);
            cout<<"st.Push():"<<a[i]<<endl;
            i++;
        }
        else{
            st.Pop(e);
            cout<<"st.pop():"<<e<<endl;
            j++;
        }
    }
    if(j == n )return true;//str是出栈序列时返回true;
    else return false;//str不是出栈序列时返回false;
}

//设计一个算法,利用顺序栈检查用户输入的表达式中的括号是否匹配
//(假设表达式中可能含有圆括号、中括号和大括号),并用相关数据
//进行测试。

bool isMatch(char str[],int n)//判断str中的括号是否匹配
{
    int i=0;char e;
    SqStackClass<char> st;
    while(i<n)
    {
        if(str[i]=='('||str[i]=='['||str[i]=='{')
        {
            st.Push(str[i]);
        }
        else
        {
            if(str[i]==')')
            {
                if(!st.Pop(e)) return false;//栈空返回false;
                if(e!='(') return false;//栈顶不是相匹配的左括号返回false;
            }
            if(str[i]==']')
            {
                if(!st.Pop(e))return false;
                if(e != '[') return false;
            }
            if(str[i]=='}')
            {
                if(!st.Pop(e)) return false;
                if(e != '{') return false;
            }
        }
        i++;//继续遍历str;
    }
    if(st.StackEmpty()) return true;//栈空返回true;
    else return false;//栈不空返回false;
}


//设计一个算法,利用顺序栈判断用户输入的字符串表达式是否为回文,
//并用相关的数据进行测试。
//解题思路:用str 存放一个表达式,建立一个顺序栈st,用i遍历str,将
//所有字符进栈,然后再次遍历str,每次退栈元素e,若当前遍历的字符str[i]
//与e不相等返回false,否则继续比较。
bool isPalindrome(char str[],int n)
{
    int i = 0;char e;
    SqStackClass<char > st;
    while(i<n)//进行入栈
    {
        st.Push(str[i]);
        i++;
    }
    while(i<n)
    {
        st.Pop(e);
        if(e!=str[i]) return false;
        i++;
    }
    return true;
}
int main()
{
    cout << "Hello world!" << endl;
    SqStackClass<char> st;

//
//    char input;
//    input = 'e';
//    str.Push(input);
//    input = 'f';
//    str.Push(input);
//    char temp;
//    while(!str.StackEmpty())
//    {
//        str.Pop(temp);
//        cout<<temp<<endl;
//    }
    int n = 5;
    char str[]="abcdafba";
    if(isPalindrome(str,n)) cout<<str<<" Y\n";
    else cout<<str<<"N\n";


    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值