按链接列表执行堆栈
问题描述:
我收到以下错误消息。 无法解决它。 Google搜索了很多。最后想到把它放在这里。按链接列表执行堆栈
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int stop;
struct stack
{
int data;
struct stack *next;
};
typedef struct stack *node, *top;
//typedef struct stack *top;
void push()
{
int i;
struct stack *x;
x = malloc(sizeof(struct stack));
printf("\n Enter the element your want to insert");
scanf("%d", &i);
x->data = i;
x->next = top;
top = x;
}
void pop()
{
int i;
if(top == NULL)
{
printf("\nStack is empty\n");
}
else{
i = top->data;
free(top);
top = top->next;
}
}
void display()
{
if(node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
}
int main()
{
int ch;
while(1)
{
printf("\nEnter your option \n1. Insert(Push) \n2. Delete(Pop) \n3. Display : \n");
scanf("%d", &ch);
switch(ch)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
default:
printf("Invalid Entery, Try Again");
}
}
return 0;
}
答
您不能将变量声明与typedef
组合起来。如果您想为struct stack
创建别名,并调用它只是stack
,修改代码如下:
struct stack {
int data;
struct stack *next;
};
typedef struct stack stack;
stack *node, *top;
答
删除typedef
,一切都会好起来的。
答
你不希望一个新的类型:
typedef struct stack *node, *top;
相反,你想新变量:
struct stack *node, *top;
非常感谢... – 2012-04-24 13:52:44
哇,这很混乱。在最后一行中,堆栈是指struct struct还是typedef struct stack stack?也许别名的另一个名字会更清晰。 – Deverill 2012-04-24 13:57:13
@Deverill同样的事情,但在最后一行'struct stack'被它的'typedef'-alias引用,而不是它的标签。使用与标签相同的别名是相对常见的做法。 – dasblinkenlight 2012-04-24 13:59:56