我在编写C语言建立一个单链表存储数据,运行没报错,却出现联机调试等对话框,希望大神看看哪里有错误。
#include<stdio.h>#include<stdlib.h>#include<malloc.h>typedefstruct//建立一个结构体{intdate;s...
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct//建立一个结构体
{
int date;
struct sqlist*next;//结构体指针
}sqlist;
int creat()//构建一个单链表
{
sqlist *p, *h,*s;
if (h = (sqlist *)malloc(sizeof(sqlist)) == NULL)
{
printf("分配失败\n");
exit(0);
}
h->next = NULL;
p = h;
for (int i = 0; p!=NULL; i++)
{
if(s= (sqlist *)malloc(sizeof(sqlist)) == NULL)
{
printf("分配失败\n");
exit(0);
}
p->next = s;
scanf_s("%d", &s->date);
s->next = NULL;
p = s;
}
return h;
}
int print(sqlist *h)
{
sqlist *p;
p = h;
for (int i = 0; i < 4; i++)
{
printf("%d ", p->date);
p = p->next;
}
}
int main()
{
sqlist *head=creat();
print(head);
} 展开
#include<stdlib.h>
#include<malloc.h>
typedef struct//建立一个结构体
{
int date;
struct sqlist*next;//结构体指针
}sqlist;
int creat()//构建一个单链表
{
sqlist *p, *h,*s;
if (h = (sqlist *)malloc(sizeof(sqlist)) == NULL)
{
printf("分配失败\n");
exit(0);
}
h->next = NULL;
p = h;
for (int i = 0; p!=NULL; i++)
{
if(s= (sqlist *)malloc(sizeof(sqlist)) == NULL)
{
printf("分配失败\n");
exit(0);
}
p->next = s;
scanf_s("%d", &s->date);
s->next = NULL;
p = s;
}
return h;
}
int print(sqlist *h)
{
sqlist *p;
p = h;
for (int i = 0; i < 4; i++)
{
printf("%d ", p->date);
p = p->next;
}
}
int main()
{
sqlist *head=creat();
print(head);
} 展开
1个回答
展开全部
三个问题
1 creat函数返回值 应该是sqlist * 而不是int
2 头结点没有存数据,打印的时候应该略过头结点
3 作为链表,不应该在打印的时候用for (int i = 0; i < 4; i++) 这样的方式,而应该判断next是否为空。
void print(sqlist *h)
{
sqlist *p;
p = h->next;
for (; p; p=p->next)
{
printf("%d ", p->date);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询