定义一个struct,包含int value和一个指针*next
#include<stdio.h>
#include<stdlib.h>
typedef struct _node{
int value;
struct _node *next;
}Node;
int main()
{
Node *head = NULL;
int number;
do
{
scanf("%d",&number);
if(number!=-1)
{
Node *p=(Node*)malloc(sizeof(Node));
p->value=number;
p->next=NULL;
Node *last=head;
if(last)
{
while(last->next)
{
last=last->next;
}
last->next=p;
}else
{
head=p;
}
}
}while(number!=-1);
Node *p;
for(p=head;p;p=p->next)
{
printf("%d\t",p->value);
}
printf("\n");
return 0;
}
定义Node *p=head
利用for(p=head;p;p->value)读取链表,for循环的第二个条件p,意思是当p!=NULL时。