#include<stdlib.h>
#include<stdio.h>
struct node{
int data;
struct node *next;
};
void create( struct node *head);
void traverse(struct node *head);
int main()
{
struct node*head=(struct node*)malloc(sizeof(struct node));
create(head);
traverse(head);
return 0;
}
void create( struct node *head)
{
int i,n;
struct node *p;
for(i=0;i<10;i++)
{
p=(struct node*)malloc(sizeof(struct node));
scanf("%d",&n);
p->data =n;
if(head==NULL)
{
head=p;
}
else
{
head->next=p;
head=p;
}
}
p->next =NULL;
}
void traverse(struct node *head)
{
struct node *t;
t=head;
while(t!=NULL)
{
printf("%d ",t->data);
t=t->next ;
}
}#include<stdlib.h>
#include<stdio.h>
struct node{
int data;
struct node *next;
};
void create( struct node *head);
void traverse(struct node *head);
int main()
{
struct node*head=(struct node*)malloc(sizeof(struct node));
create(head);
traverse(head);
return 0;
}
void create( struct node *head)
{
int i,n;
struct node *p;
for(i=0;i<10;i++)
{
p=(struct node*)malloc(sizeof(struct node));
scanf("%d",&n);
p->data =n;
if(head==NULL)
{
head=p;
}
else
{
head->next=p;
head=p;
}
}
p->next =NULL;
}
void traverse(struct node *head)
{
struct node *t;
t=head;
while(t!=NULL)
{
printf("%d ",t->data);
t=t->next ;
}
}
这个是带头结点的链表,所以输出函数修改如下
void traverse(struct node *head)
{
struct node *t;
t=head->next; //t=head;
while(t!=NULL)
{
printf("%d ",t->data);
t=t->next ;
}
}
main函数中,head不需要申请空间,在create中会进行申请,所以
struct node*head=(struct node*)malloc(sizeof(struct node));
改为struct node * head = NULL;
create函数返回值类型改为struct node *,函数最后return head;
最后main中create函数调用改为:
head = create(head);