这个是c语言数据结构中栈的代码,代码的语法没错,但运行出来的结果为空,什么都没有?有谁可以解决下!
问题描述:
这段代码是在dev c++上写的,可以运行,但没有结果!!
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct stack
{
struct node *top;
struct node *bottom;
};
void print(struct stack *s1)//打印栈
{
struct node *p;
p=s1->top;
printf("此时栈内的元素:\n");
while(p!=NULL)
{
printf("%5d",p->data);
p=p->next;
}
printf("\n");
}
struct stack *create(struct stack *s1)//创建栈
{
s1=(struct stack *)malloc(sizeof(struct stack));
struct node *p;
if(s1==NULL)
{
printf("分配内存失败!");
}
else
{
s1->top=s1->bottom=NULL;
int a[7]={67,3,88,6,1,7,0};
int i;
for(i=0;i<7;i++)
{
p=(struct node *)malloc(sizeof(struct node));
p->data=a[i];
p->next=NULL;
if(s1->top=NULL)
{
s1->top=s1->bottom=p;
}
else
{
s1->bottom->next=p;
s1->bottom=p;
}
}
}
return s1;
}
struct stack *push(struct stack *s1)//插入元素
{
printf("元素-9入栈后的结果:\n");
struct node *p;
p=(struct node *)malloc(sizeof(struct node));
p->data=-9;
p->next=NULL;
p->next=s1->top;
s1->top=p;
return s1;
}
struct stack *pop(struct stack *s1)//删除元素
{
struct node *p;
p=s1->top;
if(p==NULL)
printf("出栈失败!");
else
s1->top=p->next;
return s1;
}
void length(struct stack *s1)//求栈的长度
{
int n=0;
struct node *p;
p=s1->top;
while(p!=NULL)
{
n++;
p=p->next;
}
printf("此时栈内元素为%d个!",n);
}
int main()
{
int j=1;
struct stack *s1=NULL;
s1=create(s1);
create(s1);
print(s1);
push(s1);
print(s1);
printf("栈顶三个元素出栈后:\n");
while(j<4)
{
pop(s1);
j++;
}
print(s1);
length(s1);
return 0;
}
答
修改见注释处,供参考:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct stack
{
struct node *top;
struct node *bottom;
};
void print(struct stack *s1)//打印栈
{
struct node *p;
p=s1->top;
printf("此时栈内的元素:\n");
while(p!=NULL)
{
printf("%5d",p->data);
p=p->next;
}
printf("\n");
}
struct stack *create(struct stack *s1)//创建栈
{
s1=(struct stack *)malloc(sizeof(struct stack));
struct node *p;
if(s1==NULL)
{
printf("分配内存失败!");
}
else
{
s1->top=s1->bottom=NULL;
int a[7]={67,3,88,6,1,7,0};
int i;
for(i=0;i<7;i++)
{
p=(struct node *)malloc(sizeof(struct node));
p->data=a[i];
p->next=NULL;
if(s1->top==NULL)//if(s1->top=NULL) 修改
{
s1->top=s1->bottom=p;
}
else
{
s1->bottom->next=p;
s1->bottom=p;
}
}
}
return s1;
}
struct stack *push(struct stack *s1)//插入元素
{
printf("元素-9入栈后的结果:\n");
struct node *p;
p=(struct node *)malloc(sizeof(struct node));
p->data=-9;
p->next=NULL;
p->next=s1->top;
s1->top=p;
return s1;
}
struct stack *pop(struct stack *s1)//删除元素
{
struct node *p;
p=s1->top;
if(p==NULL)
printf("出栈失败!");
else
s1->top=p->next;
return s1;
}
void length(struct stack *s1)//求栈的长度
{
int n=0;
struct node *p;
p=s1->top;
while(p!=NULL)
{
n++;
p=p->next;
}
printf("此时栈内元素为%d个!",n);
}
int main()
{
int j=1;
struct stack *s1=NULL;
s1=create(s1);
//create(s1); //修改
print(s1);
s1=push(s1); //push(s1); 修改
print(s1);
printf("栈顶三个元素出栈后:\n");
while(j<4)
{
s1=pop(s1);// pop(s1); 修改
j++;
}
print(s1);
length(s1);
return 0;
}
答
返回值不是0就已经算是程序异常了……