使用堆栈评估表达式(C)

时间:2018-10-24 06:39:29

标签: c stack pop

我需要制作一个堆栈,以与球拍中相同的方式评估表达式。这是工作输出的示例:

Please enter the racket expression to be evaluated: 
(+ 3 (* 2 20))
+--TOP OF STACK--+
|       20        |
==================

+--TOP OF STACK--+
|       2        |
|       20        |
==================

+--TOP OF STACK--+
|       40        |
==================

+--TOP OF STACK--+
|       3        |
|       40        |
==================

+--TOP OF STACK--+
|       43        |
==================

The result is: 43

Would you like to enter another expression (Y/N)?

在这种情况下,我的pop函数可以正常工作且符合预期。当我使表达式复杂一些时,尽管pop函数停止工作。我很困惑为什么,但是因为它正在利用相同的代码。这是pop函数不起作用的输出示例:

Please enter the racket expression to be evaluated: 
(+ (*2 4) (+ 10 2))
+--TOP OF STACK--+
|       2        |
==================

+--TOP OF STACK--+
|       10        |
|       2        |
==================

+--TOP OF STACK--+
|       12        |
==================

+--TOP OF STACK--+
|       4        |
|       12        |
==================

+--TOP OF STACK--+
|       2        |
|       4        |
|       12        |
==================

+--TOP OF STACK--+
|       8        |
|       2        |
|       4        |
|       12        |
==================

+--TOP OF STACK--+
|       10        |
|       8        |
|       2        |
|       4        |
|       12        |
==================

The result is: 10

Would you like to enter another expression (Y/N)?

它对于表达式的(+ 10 2)部分正常工作,并且按预期方式弹出了10和2。然后将4和2按预期方式推送,但是当它们弹出时,它们并不会从堆栈中弹出,并且正确的数字8也被推送了,所以我知道已经调用了pop函数。我逐步检查了一下,堆栈看起来一直很好,直到到达那个位置,由于某种原因调用了pop,但是它并没有删除旧数字,只是返回了它们的值。

这是我的弹出功能:

int pop(Node** top)
{
    int pop = (*top)->digit; //stores the value to be returned.
    *top = (*top)->prev; //"pops" the top element off the stack.

    return pop; //returns the digit as an integer
}

这是推送功能:

void push(Node** stackEnd, int digit)
{
    Node* ptr = *stackEnd;        // used to traverse the list

    // set up new node
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->prev = NULL;
    newNode->digit = digit;
    newNode->next = NULL;

    // add node to linked list
    if (*stackEnd == NULL)
            *stackEnd = newNode;           // first node in list
    else
    {
            // find the end of the list
            while (ptr->next != NULL)
                    ptr = ptr->next;

            // update pointers
            ptr->next = newNode;
            newNode->prev = ptr;
    }

    // assign new endPtr
    *stackEnd = newNode;
}

这是我觉得很重要的主要部分。找到运算符后,将在底部的else语句中调用该弹出窗口:

Node* startPtr = NULL;      //nodes for linked list that will be used for the expression
    Node* endPtr = NULL;
    Node* stackEnd = NULL;      //node for the stack
    char expression[SIZE];     //variable to hold the expression the user inputs
    char again = 'Y';          //to determine if the user wants to input another expression
    int total = 0;             //used to keep track of total when evaluating the expression.
    int digit;                 //variable to store the digit that will be pushed on the stack

    //these variables will be used in determining a digit > 9
    char multDigit[SIZE] = "";
    char digitSwap[SIZE] = "";
    int j = 0;
    int k;

    do
    {
        printf("Please enter the racket expression to be evaluated: \n");
        fgets(expression, SIZE, stdin);

        for(int i = 0; i < strlen(expression); i++)        //builds the linked list for the expression using a for loop
            insertNode(&startPtr, expression[i], &endPtr);

        while(endPtr != NULL)
        {
            if(isspace(endPtr->element))                         //if the last element in the list is a space or new line we move onto the prev node
                endPtr = endPtr->prev;
            else if(endPtr->element == '(' || endPtr->element == ')')    //if the last element is a paren we move to the prev node
                endPtr = endPtr->prev;
            else if(isdigit(endPtr->element) && !(isdigit(endPtr->prev->element))) //if it is a single digit (0-9)
            {   
                digit = endPtr->element - '0';
                endPtr = endPtr->prev;
                push(&stackEnd, digit); //pushes the digit onto the stack
                printStack(&stackEnd);       //when something is pushed onto the stack we want to display the new stack to the user.
            }
            else if(isdigit(endPtr->prev->element))     //if the digit is > 9
            {
                //puts together a char array of the digit >9                
                while(isdigit(endPtr->element))
                {
                    multDigit[j] = endPtr->element;
                    endPtr = endPtr->prev;
                    j++;
                }

                //reverse it so it is in the proper order
                k = 0;

                while(j > 0)
                {
                    digitSwap[k] = multDigit[j-1];  //we need to use another variable digitSwap to store the reversed char array
                    k++;
                    j--;
                }

                digit = atoi(digitSwap); //translates the char array into an int
                push(&stackEnd, digit); //pushes the digit onto the stack
                printStack(&stackEnd);  //when something is pushed onto the stack we want to display the new stack to the user.
            }
            else //the element must be an operator(+, -, /, etc)
            {
                char operator = endPtr->element;

                total = (evaluate((pop(&stackEnd)), operator, (pop(&stackEnd)))); //pop the stack twice to evaluate
                push(&stackEnd, total);    //push the total onto the stack
                printStack(&stackEnd);       //when something is pushed onto the stack we want to display the new stack to the user.
                endPtr = endPtr->prev;
            }
        }

编辑:以防混淆我的代码的工作方式。我正在使用双向链表遍历作为字符数组的表达式。我从头到尾遍历它,例如:(+ 3 2)

expression[0]  = '(' 
expression [1] = '+'
expression[2] = ' '

等,等等...

在此示例中,我使用endPtr遍历了这些backword,然后以')'来处理我的方式backword。

1 个答案:

答案 0 :(得分:-1)

这在您的来源中看起来非常复杂。 您的堆栈只需要是一个具有最高索引的int数组。无需在多个节点上拆分表达式。 我手头没有编译器,所以这只是一个未经测试的示例

我认为您必须在对calculate()的调用中查看pop()的正确顺序

int stack[64], stacktop=-1;

void push(int val) {
    stacktop++;
    stack[stacktop] = val;
}
int pop() {
    return (stacktop>=0) ? stack[stacktop--] : 0;
}

int evaluate(char *buf) {
    char *ptr, *mark, *pcpy, *pcpy2, buf2[256];

    for(ptr=buf; *ptr ; ptr++);    // goto end of buf
    for(ptr--; ptr>=buf; ptr--) {
        if(isspace(*ptr)) continue;
        if(*ptr=='(' || *ptr==')') continue;
        for(mark=ptr; ptr>=buf && isdigit(*ptr); ptr--); // test for digits
        if(ptr!=mark) {                                  // found at least 1 digit
            ptr++;
            for(pcpy2=buf2, pcpy=ptr; pcpy<=mark; pcpy++, *pcpy2++)
                *pcpy2=*pcpy;
            *pcpy2='\0';
            push(atoi(buf2));
            continue;
        }
        if(*ptr=='+' || *ptr=='-' || *ptr=='*' || *ptr=='/') {
            push(calculate(pop(), *ptr, pop()));
        }
    }
    return pop();
}