单链表的建立

1.单链表的建立
/**************************************
功能:创建一个单链表,并依次打印出链表中的元素
****************************************/

#include<stdio.h>
#include<malloc.h>

struct node

{
int data;
node *next;

};

node *creat(int n)
{
node *head,*p1, *p2;

int a;
head=NULL;

for(int i=1;i<=n;i++)
{
p1=(node*)malloc(sizeof(node));
printf("请输入第 %d个数:",i);
scanf("%d",&a);
p1->data=a;
if(head==NULL)
{
head=p1;
p2=p1;//链表只有一个元素

}
else
{
p2->next=p1;
p2=p1;

}
p2->next=NULL;

}
return head;
}

int main()
{

int b;
node *q;
scanf("%d",&b);
q=creat(b);
while(q!=NULL)
{
printf("%d ",q->data);

q=q->next;
}


}




测试结果:

猜你喜欢

转载自blog.csdn.net/jishuwenming/article/details/52760976