【问题标题】:Implementing a linked list with a stack in C在 C 中实现带有堆栈的链表
【发布时间】:2014-03-19 01:59:56
【问题描述】:

对于预实验(意味着它不是为了成绩),我应该使用链表实现我的第一个堆栈。我写它时只在堆栈中添加了一件东西,就像练习一样,为什么它这么短。无论如何,我没有编译错误,除了它说“new”在我的 create_stack 函数中未初始化。这也是我遇到分段错误的地方,因为它没有打印出我的第一个 printf 函数。我也猜测问题不仅仅是我初始化堆栈,但这是我的问题的开始。如果事情很简单,请放轻松,就像我说的,这是我第一次做堆栈,感谢您的帮助。

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

typedef struct node_{
    char data;
    struct node_ *next;
}node;

typedef struct stack_{
    unsigned int size;
    node* stack;
}stack;

stack* create_stack();
void push(stack* s, char val);
char top(stack* s);
void pop(stack*s);

int main(void) {

    char value, val;

    stack* new = create_stack();

    printf("Enter a letter: ");
    scanf("%c", &value);

    push(new, value);

    val = top(new);

    printf("%c\n", val);

    pop(new);

    return 0;
}

stack* create_stack(){ //initializes the stack

    stack* new;

    new->size = 0;
    new->stack = NULL;

    return new;

}

void push(stack* s, char val) {

    node* temp = (node*)malloc(sizeof(node)); //allocates 

    if ( temp == NULL ) {
        printf("Unable to allocate memory\n");
    }

    else{
        temp->next = s->stack;
        temp->data = val;
        s->stack = temp;
        s->size = (s->size) + 1; //bumps the counter for how many elements are in the stack
    }

}

void pop(stack* s) {

    node* temp;

    temp = s->stack;
    s->stack = temp->next;
    free(temp);
    s->size = (s->size) - 1; //subtracts from counter

}

char top(stack* s) {

    node* temp = s->stack;

    char value = temp->data;

    return value;
}

【问题讨论】:

    标签: c linked-list stack


    【解决方案1】:

    它崩溃的原因是您在创建堆栈时从未分配任何内存。在 create_stack 函数中执行stack* new = malloc (sizeof(stack));

    对于未来,您可能希望使用更好的变量名。例如,使用new 作为堆栈的名称并不是那么好 - 它不是很有描述性,而且它是多种语言中的保留关键字,例如 C++。

    【讨论】:

    • 谢谢!现在可以了。我认为这很简单……它总是如此!
    【解决方案2】:

    stack *new 创建一个本地指针,但它还没有指向任何东西。由于您希望堆栈在函数完成后继续存在,因此您应该使用 malloc 为其分配内存(并最终使用 free 释放它)。

    所以你的 create_stack 函数应该以:

    stack* new = malloc(sizeof(stack));
    

    另一种方法是将堆栈声明为主函数中的局部变量,并将其作为参数传递给 create_stack 以对其进行初始化:

    stack new;
    create_stack(&new);
    

    【讨论】:

      猜你喜欢
      • 2012-05-24
      • 2019-03-04
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      • 2013-03-17
      • 1970-01-01
      • 2014-12-18
      相关资源
      最近更新 更多