一个简单的链表输出

来源:百度知道 编辑:UC知道 时间:2024/06/08 10:22:11
#include "stdio.h"
#include "malloc.h"
#define len sizeof(struct node)
struct node{
int data;
struct node *next;
};

struct node *scanff()
{
struct node *p1;
struct node *head;
int n=0;
struct node *p2;
p1=p2=(struct node *)malloc(len);
scanf("%d",&p1->data);
head=0;
while(p1->data!=0)
{
n++;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct node *)malloc(len);
scanf("%d",&p1->data);
}
p2->next=0;
return(head);
}

void print(struct node *head)
{
struct node *p;
p=head;
if(head!=0)
do{
printf("%d ",p->data);
p=p->next;
}while(p!=0);
}

void main()
{
struct node *head;
head=scanff();
print(head);
}

请各位帮忙看一下这个链表输出程序出现了什么问题,当我输入一些数的时候它没有输

怎么会没有输出呢?因为你并没有结束程序
while(p1->data!=0)
{
n++;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct node *)malloc(len);
scanf("%d",&p1->data);
}
注意这个while循环,是当p1->data=0时退出,因此你必须输入0结束输入才会有输出我改了一下程序这样更直观些

#include "stdio.h"
#include "malloc.h"
#define len sizeof(struct node)
struct node{
int data;
struct node *next;
};

struct node *scanff()
{
struct node *p1;
struct node *head;
int n=0;
struct node *p2;
p1=p2=(struct node *)malloc(len);
printf("请连续输入整数 输入0停止\n");
scanf("%d",&p1->data);
head=0;
while(p1->data!=0)
{
n++;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct node *)malloc(len);
scanf("%d",&p1->data);
}
p2->next=0;
return (head);
}