中缀到Postfix函数返回空字符串

时间:2017-10-14 06:48:52

标签: c++ function postfix-notation infix-notation

所以我有这个函数,它接受一个中缀表达式并返回等效的后缀表达式。但是,它返回一个空字符串。我不确定为什么。

string postfixUtility::getPostfix(string infix)
{
    std::stack<char> st;
    st.push('N');
    int length = strlen(string.c_str());
    std::string pexp;
    for (int i = 0; i < length; i++)
    {
        if (string[i] == '(')
        {
            st.push('(');
        }
        else if (string[i] == ')')
        {
            while (st.top() != 'N' && st.top() != '(')
            {
                char c = st.top();
                st.pop();
                pexp += c;
            }
            if (st.top() == '(')
            {
                char c = st.top();
                st.pop();
            }

        }
    }
    while (st.top() != 'N')
    {
        char c = st.top();
        st.pop();
        pexp += c;
    }
    return pexp;
}

它基于此头文件:

#ifndef POSTFIX_UTILITY_H_
#define POSTFIX_UTILITY_H_

using namespace std;

class postfixUtility
{
public:
    postfixUtility();
    std::string getPostfix(string infix);
    float evaluatePostfix(string pexp);
};



#endif //POSTFIX_UTILITY_H_

堆栈操作基于此链表:

#ifndef GENERIC_LINKED_LIST_STACK_H_
#define GENERIC_LINKED_LIST_STACK_H_
#include "Node.h"
#include <cstring>
#include <iostream>

template <class Type>
class genericLinkedListStack
{
    public:
        genericLinkedListStack();
        int size() const;
        void push(Type element);
        Type pop();
        bool empty() const;
        int top();

    private:
        node <Type> *first;     
};

template <class Type>
int genericLinkedListStack<Type>::size() const
{
    node<Type> *newNode;
    newNode = new node<Type>;
    int count = 0;
    while (newNode!= NULL)
    {
        count++;
        newNode = newNode->next;
    }
    return count;
}

template <class Type>
void genericLinkedListStack<Type>::push(Type element)
{
    node<Type> *newNode;
    newNode = new node<Type>;
    newNode -> data = element;
    newNode -> next = first;
    first = newNode;
}

template <class Type>
Type genericLinkedListStack<Type>::pop()
{
    node<Type> *current = first;
    Type element = current -> data;
    delete current;
    return element;
}

template <class Type>
bool genericLinkedListStack<Type>::empty() const
{
    return first == NULL;
}

template <class Type>
genericLinkedListStack<Type>::genericLinkedListStack()
{
    first = NULL;
}

template <class Type>
int genericLinkedListStack<Type>::top()
{
    return first->data;
}


#endif // GENERIC_LINKED_LIST_STACK_H_

我知道它返回一个空字符串,因为我需要在另一个函数中评估后缀表达式,但它从不进入for循环,因为我将i初始化为0,从而检查我是否小于长度。这始终给我一个分段错误。

感谢您的帮助!

0 个答案:

没有答案