stos

0

Napisz program, w którym zaimplementujesz stos na bazie tablicy. Liczbę elementów tablicy dobierz samodzielnie. Przetestuj tę implementację. Twój program powinien wykrywać sytuacje, kiedy stos jest pusty i kiedy jest pełny. Mam takie zadnie, zrobilam kod ale nie wyswietla mi poprawnie wartosci

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

#define STACK_SIZE 10

struct stack
{
    int data[STACK_SIZE];
    int top;
    struct stack_node *next;
};

struct stack_node
{
    int data[STACK_SIZE];
    struct stack_node *next;
};

struct stack_node *push(struct stack_node *top, int data[])
{
    struct stack_node *new_node=NULL;
    new_node = (struct stack_node*)malloc(sizeof(struct stack_node));
    if (new_node != NULL)
    {
        new_node->data[STACK_SIZE] = data[STACK_SIZE];
        new_node->next = top;
        top = new_node;
    }
    return top;
}

int pop(struct stack_node **top)
{
    int result =-1;
    if (*top != NULL)
    {
        result=(*top)-> data[STACK_SIZE];
        struct stack_node *tmp=(*top)->next;
        free(*top);
        *top=tmp;
    }
    return result;
}

int peek (struct stack_node *top)
{
    if (top != NULL)
        return top->data[STACK_SIZE];
    fprintf(stderr, "Stos nie istnieje\n");
    return -1;
}

int main ()
{

    struct stack_node *top=NULL;
    int data[STACK_SIZE];
    int i;
    srand(time(0));
    for (i=0; i<STACK_SIZE; i++)
        {
            data[i]=1+rand()%10;
            printf("%d", data[i]);
            puts("");
        }

    {
        top=push(top, data);
        printf("klade element %d na stos\n",data);
    }
    printf("\nczytam element na szczycie bez zdejmownia, wartosc: %d\n", peek(top));

    while (top != NULL)
    {
        printf("\nzdejmuje element %d ze stosu \n", pop(&top));
    }
    return 0;
}
3

Dlaczego mając za zadanie zaimplementować stos za pomocą tablicy, implementujesz go za pomocą listy jednokierunkowej?

0

Ta tablica data ma być Twoim wewnętrznym stosem o stałym rozmiarze.

0

Poprawna definicja ta struktury to

struct stack
{
    int data[STACK_SIZE];
    int top;
};

1 użytkowników online, w tym zalogowanych: 0, gości: 1