C 中的堆栈抽象数据类型 [英] Stack abstract data type in C

查看:38
本文介绍了C 中的堆栈抽象数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能告诉我我做错了什么吗?我收到 SIGSEGV(分段错误)错误.单链表是实现堆栈抽象数据类型的最佳方式吗?我尽量不使用全局变量,所以这就是我使用双指针的原因.

Can you please tell me what I did wrong? I'm getting SIGSEGV (Segmentation fault) error. Is single linked list the best way to implement a stack abstract data type? I'm trying not to use global variables so that's why I used double pointers.

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

typedef struct stack{
    int data;
    struct stack *next;
}STACK;

void push(STACK **head,STACK **tail,int n)
{
    STACK *x;
    if(*head==NULL)
    {
        (*head)=malloc(sizeof(STACK));
        (*head)->data=n;
        (*head)->next=NULL;
        *tail=*head;
    }
    else
    {
        x=malloc(sizeof(STACK));
        x->data=n;
        x->next=NULL;
        (*head)->next=x;
        (*head)=(*head)->next;
    }
}

void show(STACK *tail)
{
    if(tail!=NULL)
    {
        printf("From tail to head:\n");
        while(tail!=NULL)
        {
            printf("%d\n",tail->data);
            tail=tail->next;
        }
    }
    else
    {
        printf("The stack is empty!\n");
    }
}

void pop(STACK **head,STACK *tail)
{
    STACK *x;
    if(*head!=tail)
    {
        x=*head;
        while(tail->next->next!=NULL)
            tail=tail->next;
        printf("pop: %d\n",(*head)->data);
        *head=tail;
        free(x);
    }
    else
    {
        printf("pop: %d\n",(*head)->data);
        free(*head);
        *head=NULL;
    }
}

int main()
{
    STACK *head = NULL;
    STACK *tail = NULL;
    push(&head,&tail,4);
    pop(&head,tail);
    push(&head,&tail,7);
    push(&head,&tail,9);
    show(tail);
    return 0;
}

我编辑了代码,现在可以使用了.谢谢大家!!!

I edited the code, now it works. Thank you everyone!!!

推荐答案

最直接的问题是你永远不会在 main() 中初始化 headtail:

The most immediate problem is that you never initialize head and tail in main():

STACK *head = NULL;
STACK *tail = NULL;

还有其他几个问题:

  1. pop() 泄漏内存.
  2. 如果列表为空(即 tailNULL),
  3. show() 将不起作用.
  4. 当列表不为空时,show() 无法打印其元素之一.
  1. pop() leaks memory.
  2. show() won't work if the list is empty (i.e. tail is NULL).
  3. When the list is not empty, show() fails to print one of its elements.

这篇关于C 中的堆栈抽象数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆