Почему мне нужно привести "((node) s-> top) -> next = q" к методу "pu sh"? Дублирует указатель объявления на структуру - PullRequest
0 голосов
/ 22 апреля 2020

Я хотел бы получить объяснения относительно некоторых дабов. Вот код:

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

typedef struct sNode {
    int data;
    struct sNode* next;
} sNode;

typedef sNode* node;

typedef struct {
    node *top;
    node *head;
    int nodes;
} stack;

void push(stack *s);
void printStack(stack *s);


int main(){
    srand((unsigned)time(NULL));
    stack s = {NULL, NULL, 0};
    push(&s);
    push(&s);
    push(&s);
    push(&s);
    printStack(&s);
    return 0;
}

void push(stack *s){
    node q = (node)malloc(sizeof(sNode));
    q->data = rand() % 10 + 1;
    q->next = NULL;
    if(s->top){
        ((node)s->top)->next = q;
        s->top = q;
    } else {
        s->top = q;
    }
    if(s->nodes == 0) s->head = q;
    s->nodes++;
}

void pop(stack *s){

}

void printStack(stack *s){
    printf("Number of nodes: %d\n", s->nodes);
    node q = s->head;
    while(q != NULL){
        printf("%d -> ", q->data);
        q = q->next;
    }
    printf("NULL");
}

Можете ли вы объяснить мне, почему мне нужно привести (* узел) к функции pu sh? Почему также достаточно объявить указатель на структуру следующим образом:

stack *s;

и начать работать? Какая разница с этим:

stack s;
stack *ss = &s;
...