主函数中 linkstack t 无法被初始化。 怎么弄???
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define TRUE 1
#define ERROR 1
#define stack_size 50
typedef int stackelementtype;
typedef struct node
{
stackelementtype data;
struct node *next;
}linkstacknode;
typedef linkstacknode *linkstack;
void in(linkstacknode *temp)
{
temp=(linkstacknode*)malloc(sizeof(linkstacknode));
}
int push(linkstack top,linkstacknode *temp,stackelementtype x)
{
temp->data=x;
temp->next=top->next;
top->next=temp;
return (TRUE);
}
int pop(linkstack top,stackelementtype *x)
{
linkstacknode *temp;
temp=top->next;
if(temp==NULL) return (ERROR);
top->next=temp->next;
*x=temp->data;
printf("删除之后首元素为:");
printf("%d",top->next);
free(temp);
return(TRUE);
}
int main()
{
linkstacknode n;
linkstack t;
int i=0;
int m;
stackelementtype ys;
in(&n);
printf("请输入链栈的元素个数:");
scanf("%d ",i);
printf("请输入链栈的元素:");
for(int k=1;k<=i;k++)
{
scanf("%d ",&m);
push( t,&n,m);
}
printf("现在弹出首元素……");
pop( t,&ys);
return 0;
}
[解决办法]
我写了个:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#define TBL(arr) (sizeof(arr)/sizeof((arr)[0]))
typedef struct stu_info
{
int num;
char name[20];
int age;
}ElemType;
//链栈结点的定义
typedef struct _stack
{
ElemType data;
struct _stack *next;
}stack_t;
int push(stack_t **top, ElemType * pelem);
int pop(stack_t **top, ElemType * pelem);
int main(void)
{
int i;
ElemType elem;
stack_t *top = NULL;
ElemType stus[] = {
{1001,"zhangsan",20},
{1002,"lisi", 21},
{1003,"wangwu", 22}
};
for(i = 0; i < TBL(stus); i++)
{
memcpy(&elem,stus+i,sizeof(ElemType));
if(push(&top, stus+i) == -1)
{
goto _out;
}
}
while(top!=NULL)
{
if(pop(&top, &elem) == -1)
{
goto _out;
}
printf(" 学号 :%4d, 姓名 :%10s,年龄:%2d\n",elem.num,elem.name,elem.age);
}
return 0;
_out:
return -1;
}
//入栈
//成功返回 0,不成功返回 -1
int push(stack_t **top, ElemType * pelem)
{
stack_t *p;
//判断入栈元素地址的合法性
if(NULL ==pelem)
{
return -1;
}
//申请栈元素地址空间
p=(stack_t *)malloc(sizeof(stack_t));
//判断是否申请成功
if(NULL ==p)
{
return -1;
}
//栈元素赋值
memcpy(&(p->data),pelem,sizeof(ElemType));
//元素入栈
p->next = *top;
*top = p;
return 0;
}
//出栈
//成功返回 0,不成功返回 -1
int pop(stack_t **top, ElemType * pelem)
{
stack_t *p;
//判断栈是否为空
if( NULL==*top)
{
return -1;
}
//判断接收栈元素地址的合法性
if(NULL ==pelem)
{
return -1;
}
//拷贝栈顶元素
memcpy(pelem,&((*top)->data),sizeof(ElemType));
//出栈
p=*top;
*top=p->next;
//释放原栈顶元素空间
free(p);
return 0;
}