Questions about implementing Stack!

Asked 2 years ago, Updated 2 years ago, 60 views

typedef struct stack* Stack; typedef char element;

struct stack { element* array; int size; int top; };

int IsEmpty(Stack S) { return (S->top<0); }

int IsFull(Stack S) { return ((S->top+1) == S->size); }

Stack createStack (int c) { Stack S = (Stack)malloc(sizeof(struct stack));

S->size = c;
S->top = -1;
S->array = (element *)malloc(sizeof(element) * c);

return S;

}

Stack makeEmptyStack(Stack S) {. S->top = -1;

return S;

}

void push (element X, Stack S) { if (IsFull(S)) { printf ("Out of Space\n"); return; }

S->array[++(S->top)] = X;
printf("push finishde");

}

element pop(Stack S) {
if(IsEmpty(S)) { printf ("Nothing on Stack\n"); return 0; }

return (char)S->array[(S->top)--];

}

void deleteStack(Stack S) {
free(S); return; }

void main () { element present; element str[100] = {0}; int i = 0, j = 0, count = 0; int rcount = 0, lcount = 0;

Stack S = createStack(100);


while(1) {
    scanf("%s", & present); // 1 character entered. 
    count++; // repeat this much when output later. 

    If (present == '!') exit(1); // '!' is met and terminated. 

    If (present == '(') { // '('), count and push.
        lcount++;

        push(present, S);
    }

    If you meet else if (present == '') { // '', count and pop it until '(' comes out and save it in str. 
        rcount++;

        while(pop(S) != '(') {
            str[j++] = pop(S);
        }
    }
    else if (present == '#') { // When you meet '#', right or wrong, and print out what you saved in str in order. Then initialize and run again. 

        if (rcount==lcount) {
            printf("right. ");
        }
        else {
            printf("wrong. ");
        }
        for(i = 0; i < count; i++) {
            printf("%c ", str[i]);      
        }
        printf("\n");

        //Initialization 
        S = makeEmptyStack(S);

        for(i = 0; i < count; i++){
            str[i] = '\0';
        }
        rcount, lcount, j, count = 0;
        //
    }
    else push(present, S); // If nothing is applicable, just push. 
    printf("1");
}
deleteStack(S);

}

ab (cd) ef # If you type it like this

Compare the number of ( and ) and return right if they are equal to each other, and wrong if they are different.

I'm working on a program that prints it out in this order, but the program keeps stopping.

So I made sure that 1 is being printed every time I go around the loop of the while door, but 1 is not output at all. I don't know where it went wrong anymore..

What's the problem?

stack

2022-09-21 23:09

1 Answers

Stack makeEmptyStack (Stack S) {. S->top = -1;

return S;
}

Clear this part {Next time, try it


2022-09-21 23:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.