Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

linked list - C: Evaluating Expression in a queue not working

I have created a queue using linked list that takes a string in the format 1 + 3 + 5 =or 1-3+2-4 = but the following code which is supposed to do the calculation given the sign and produce the answer is not working right for example if I passed a string like 66 - 31 - 21 + 43 = is passed the answer turns out to be -47 instead of 57. Can someone help me solve it or point to what I'm doing wrong.

void printQueue(struct node* head)
{
    struct node* temp;
    char *token, *del=" ";
    int total = 0;

    while (head != NULL)
    {

        token = strtok(head->data, del);
        while (token != NULL) {
            int a = strcmp(token, "+");
            int b = strcmp(token, "-");
            if (a == 0)
            {
                printf("+");
                total = total + *token;
            }
            else if (b == 0) {
                printf("+");
                total = total - *token;
            }

            printf("%s ", token);
            token = strtok(NULL, del);
        }

        printf(" %d
",subtraction);
        head = head->next;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your code is ignoring the numbers, adding up character codes of '+' and '-' characters instead. The number -47 is the result of computing -45-45+43: 45 is the character code for the dash; 43 is the character code for the plus.

In order to work properly, make these changes to your code:

  • Add a sign variable of int type, with the initial value of 1
  • When you see a plus sign, set the sign to 1
  • When you see a minus sign, set the sign to -1
  • When you see a token that is neither a plus nor minus, convert it to an int val (e.g. by calling atoi), and add val * sign to the running total.

This change will make your code work for valid expressions, but it would not fail for some invalid ones. For example, it would take "expressions" such as 1 2 3 as if it were 1+2+3, and so on.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...