使用链表的堆栈实现不起作用

时间:2018-10-09 15:28:31

标签: c linked-list

我目前正在使用C语言中的链表(LIFO)来实现堆栈。我已经阅读了一些教程,并发表了一些关于堆栈溢出的文章,并提出了以下解决方案。

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

typedef struct node
{
   char string[20];
   struct node *next;
} node;

node *push(char *element, node *head);
node *pop(node *head);
void destroy_stack(node *p);

int main(void)
{


    // create new stack
    node *stack = NULL;

    // push 6 "functions" to the stack
    char *function[6] = {"first funct", "second funct", "third funct",
    "fourth funct", "fifth funct", "sixt funct"};       
    for (int i = 0; i < 6; i++)
    {
        printf("function is : %s\n",function[i]);
        stack = push(function[i], stack);
        if (!stack)
        {
            fprintf(stderr,"Not enough memory space for new list");
            return 1;
        }
    }


    // display the stack
    for (node *temp = stack; temp != NULL; temp = temp -> next)
    {

        printf("Elements of the stack are: %s\n", temp -> string);
    }

    // pop the elements from the stack
    while (stack != NULL)
    {

        printf("Popped elemet is: %s\n", stack -> string);
        stack = pop(stack);


    }

    destroy_stack(stack);
    return 0;

} 

node *push(char *element, node *head)
{
    // create space for new element on stack
    node *temp = sizeof(node);
    if (!temp)
    {
        return NULL;
    }

    // if stack is empty
    if (head == NULL)
    {
        strcpy(temp -> string, element);
        temp -> next = NULL;
        return temp;
    }

    strcpy(temp -> string, element);
    temp -> next = head;
    return temp;
}

node *pop(node * head)
{
    // create a new head
    node *newHead = head->next;

    // pop the element from stack
    free(head);

    return newHead;

}

void destroy_stack(node *p)
{
    if ( p == NULL )
    {
        return;
    }
    else
    {
        destroy_stack(p -> next);
    }
    free(p);
}

但是我的代码无法正常工作,无法理解为什么缺乏C编程知识会导致这种情况发生。有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

此行是错误的:

node * temp = sizeof(node);

您只需将节点的大小放到temp指针中,而不是分配内存,这会触发编译器警告。

应该是:

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

您没有收到编译器警告吗?

旁注

您不应该在destroy_stack中使用递归,只需一个简单的循环即可。

答案 1 :(得分:1)

您只是搞砸了push函数中的动态内存分配。必须对此进行以下纠正。

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