问题 Stack 使用链表实现

problem Stack implementaion using a linked list

我试图用链表实现堆栈,但似乎遇到了 'segmentation error' 。代码似乎编译并且 运行 但是当我实际在标准输入中输入 'times' int 变量的值时。该代码显示分段错误。 scanf 也没有显示格式化的字符串。

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define NAME_MAX 40

struct NODE{
    char name[NAME_MAX];
    int regno;
    int age;
    struct NODE* next;
};

struct STACK{
    struct NODE *head;
    int size;  
};

void printStack(const struct STACK *stack);
bool pushStack(struct STACK *stack);
bool makeStack(struct STACK *stack, int data_count);
void cleanStack(struct STACK *stack);

int main(){
    struct STACK list = {NULL,0};
    int times = 0;
    scanf("How many data you want to enter: %d", &times);
    if(!makeStack(&list, times)){
        fprintf(stderr, "Stack wasn't created\n");
    }
    printStack(&list);
    cleanStack(&list);
    return 0;
}

void cleanStack(struct STACK *stack){
    struct NODE *trav = stack->head;
    while(trav!=NULL){
        struct NODE *temp = trav;
        trav = trav->next;
        temp = NULL;
    }
}

void printStack(const struct STACK *stack){
    struct NODE *trav = stack->head;
    for(int counter=1; stack!=NULL; trav=trav->next,++counter,++stack){
        printf("%d: %s %d %d",counter,trav->name,trav->regno, trav->age);
    }
}

bool makeStack(struct STACK *stack, int data_count){
    while(data_count--){
        if(!pushStack(stack)){
            return false;
        }
    }
    return true;
}

bool pushStack(struct STACK *stack){
    struct NODE *temp = malloc(sizeof(struct NODE));
    if(temp==NULL) return false;
    scanf("Input Name: %s", temp->name);
    scanf("Input RegNo: %d", &temp->regno);
    scanf("Input age: %d", &temp->age);
    temp->next = stack->head;
    stack->head = temp;
    ++stack->size;
    return true;
}

您的实施存在一些问题。

您必须先使用 printf 打印到 stdout,然后您可以使用 scanf.

扫描输入
printf("Number of data points: ");
scanf("%d", &times);

而在printStack函数中,需要用while循环遍历链表

void printStack(const struct STACK *stack)
{
    struct NODE *trav = stack->head;
    int counter = 1;
    while (trav != NULL) {
        printf("%d: %s %d %d\n", counter, trav->name, trav->regno, trav->age);
        trav = trav->next;
        counter++;
    }
}

而在 cleanStack 中,我会 free(temp) 而不是将其设置为 NULL

顺便说一下...你不需要,但你可以像这样为 struct Node *temp 分配内存(在我看来它看起来更好):

struct NODE *temp = malloc(sizeof *temp);