Stack-related questions

Asked 1 years ago, Updated 1 years ago, 119 views

When I run the Stop function, I need to show the last data that went in, but it doesn't come outDo you know what the problem is?

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

#define TRUE 1
#define FALSE 0  
#define STACK_LEN 10001


typedef struct _Stack
{
    int arr[STACK_LEN];
    int topIndex;
}  }  ST;

void SstackInit(ST *pstack)
{
    pstack->topIndex = -1;
}

void Spush(ST *pstack, int X)
{
    pstack->topIndex += 1;
    pstack->arr[pstack->topIndex] = X;
}

int Sempty(ST *pstack)
{
    if (pstack->topIndex == -1)
        return TRUE;
    else
        return FALSE;
}

int Spop(ST *pstack)
{
    int imsi;

    if (Sempty(pstack))
    {
        printf("error!");
        return -1;
    }

    imsi = pstack->topIndex;
    pstack->topIndex -= 1;
    return pstack->arr[imsi];

}   

int Ssize(ST *pstack)
{   
    It starts with return pstack->topIndex + 1; //-1

}

int Stop(ST *pstack)
{
    if (Sempty(pstack))
    {
        return -1;
    }

    return pstack->arr[pstack->topIndex];
}


int   main()
{
    ST stack;
    char str[10];
    int N = 0, i, num;


    scanf("%d", &N);

    SstackInit(&stack);

    for (i = 0; i < N; i++)
    {
        scanf("%s", str);


        if (!strcmp(str, "push"))
        {
            scanf("%d", &num);

            Spush(&stack, num);
        }

        else if (!strcmp(str, "pop"))
        {
            printf("%d\n", Spop(&stack));
        }


        else if (!strcmp(str, "size"))
        {
            printf("%d\n", Ssize(&stack));
        }


        else if (!strcmp(str, "empty"))
        {
            printf("%d\n",Sempty(&stack));
        }

        else if (!strcmp(str, "top"))
        {
            printf("%d\n", Stop(&stack));
        }



    }

    return 0;
}

c stack

2022-09-22 18:47

1 Answers

The code is running well. However, else if (!strcmp(str, "top")) { printf("%d\n", Stop(&stack)); If "top" changes to "stop" in }, that would be perfect.


2022-09-22 18:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.