读入一批数据,遇到负数停止,将读入的正数组成先进先出链表并输出

来源:百度知道 编辑:UC知道 时间:2024/05/24 02:41:11

这是一般的做法,还可以改成函数调用版的,你自己思考一下吧

#include<malloc.h>
#include<stdio.h>
#define null 0

struct shu
{ int a;
struct shu *next;
};

void main( )
{

struct shu *head , *p1 , *p2,*p;

p1= (struct shu *) malloc (sizeof (struct shu)) ;
scanf("%d", &p1->a) ;

if (p1->a<0)
{
printf("为空链表");
goto end;
}

head=p2=p1;

while( p1->a>=0)
{
p1=(struct shu *) malloc(sizeof (struct shu)) ;
scanf("%d", &p1->a);
if (p1->a<=0)
p2->next=null; /* head 指向第一个结点 */
else
{
p2->next=p1 ; /* 将新结点 p1 链入链表 */
p2=p1 ;
} /* 保留当前结点的地址 */
}
p2->next=null;

printf("输出结点数据 :\n")