Невозможно получить доступ к главному узлу связанного списка вне блока else в цикле while - PullRequest
0 голосов
/ 07 апреля 2020

Этот код на самом деле предназначен для преобразования инфиксного выражения в постфиксное преобразование. Несмотря на то, что я все еще должен полировать sh мой код, я столкнулся с проблемой. Я строю стек через связанный список, в котором хранятся операторы и который основан на их значение напечатано. Я запускаю для l oop по всему инфиксному выражению (которое сохраняется в виде строки) и печатаю операнды непосредственно на консоль, но складываю операторы. Через некоторое время я хотел * oop распечатать содержимое стека, но я понял, что он не может получить доступ к указателю головы снаружи, в то время как l oop.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

#define MAX_CAP 100

struct charc {  //struct definition
    char operator;
    struct charc *nxt;
};

void
pushst(struct charc **head, char opera)//to push nodes in the stack
{
    struct charc *temp;

    temp = (struct charc *) malloc(sizeof(struct charc));
    temp->operator = opera;
    temp->nxt = NULL;
    if (*head == NULL)
        *head = temp;
    else {
        struct charc *temp1 = *head;

        while (temp1->nxt != NULL)
            temp1 = temp1->nxt;

        temp1->nxt = temp;
    }
}

void
popst(struct charc **head)//to pop the top most node in the stack
{
    if (*head == NULL)
        exit(EXIT_SUCCESS);
    else {
        struct charc *temp = *head;
        struct charc *prev = *head;

        while (temp->nxt != NULL) {
            prev = temp;
            temp = temp->nxt;
        }

        prev->nxt = NULL;
        free(temp);
        temp = NULL;
    }
}

/*int troperand(char c)
{
    if (c>='0'&&c<='9')
    return 1;
}*/

int
operator(char c)//preference order of the operators
{
    switch (c) {
    case '+':
        return 0;
    case '-':
        return 0;
    case '*':
        return 1;
    case '/':
        return 1;
    case '^':
        return 2;
    default:
        exit(EXIT_SUCCESS);
    }
}

char
printtop(struct charc **head)
{
    struct charc *temp = *head;

    while (temp->nxt != NULL)
        temp = temp->nxt;
    return temp->operator;
}

struct charc *
convo(struct charc **head)
{

    printf("Enter the infix expression:\n");
    char str[MAX_CAP],
     ch;
    int j = 0;

    while (ch != '\n') {
        ch = getchar();
        str[j] = ch;
        j++;
    }
    str[j] = '\0';

    int i = 0;

    while (str[i] != '\0') {
        if (isdigit(str[i]) != 0)
            printf(" %c", str[i]);

        else if (str[i] == '.')
            printf(" %c", str[i]);

        else if (str[i] == '(') {
            pushst(head, str[i]);

        }

        else if (str[i] == ')') {

            while (*head != NULL && printtop(head) != '(') {
                struct charc *temp = *head;

                while (temp->nxt != NULL)
                    temp = temp->nxt;
                printf(" %c", printtop(head));
                popst(head);

            }
            if (printtop(head) == '(') {
                printf("\nInvalid expression\n");
                break;
            }

        }
        else {
            while (*head != NULL && operator(str[i]) <= operator(printtop(head))) {
                printf(" %c", printtop(head));
                popst(head);
            }
            pushst(head, str[i]);
            // printf("%c",printtop(head));

        }

        i++;

    }

    printf("%c", printtop(head));
    return *head;
}

int
main(void)
{
    struct charc *head = NULL;
    struct charc *newhead = convo(&head);

    // printf("%c",newhead->operator);
    while (newhead != NULL) {
        printf(" %c", printtop(&newhead));
        popst(&newhead);
    }

    return 0;
}

Я пытался поместить while l oop в convo () функция, но это порождает ту же проблему. Если я печатаю верхнюю часть стека внутри, в то время как l oop показывает верх, что означает, что оператор помещается в стек, но то же самое, если я пытаюсь сделать это снаружи пока l oop он не печатает его. Я не могу понять, где я ошибся. ты мне поможешь с этим? Я дал 2 * 3 в качестве ввода, но вместо 2 3 * в качестве вывода он дал 2 3 в качестве вывода.

...