【发布时间】:2012-02-09 14:19:41
【问题描述】:
你能告诉我我做错了什么吗?我收到 SIGSEGV(分段错误)错误。单链表是实现堆栈抽象数据类型的最佳方式吗?我试图不使用全局变量,所以这就是我使用双指针的原因。
#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;
}
我编辑了代码,现在它可以工作了。谢谢大家!!!
【问题讨论】:
-
不要在 C 中转换 malloc 的结果。仅在 C++ 中。
标签: c stack abstract-data-type