顺序建立链表

来源:互联网 发布:网络聊天用语段子 编辑:程序博客网 时间:2024/04/28 15:08

#include<stdio.h>
#include<malloc.h>
struct node
{
 int data;
 struct node *next;
};
struct node *creat(int n)
{
 int i;
 struct node *head,*tail,*p;
 head=(struct node *)malloc(sizeof(struct node));
 head->next=NULL;
 tail=head;
 for(i=1;i<=n;i++)
 {
  p=(struct node *)malloc(sizeof(struct node));
  scanf("%d",&p->data);
  p->next=NULL;
  tail->next=p;
  tail=p;
 }
 return head;
}
void print(struct node *head)
{
 struct node *p;
 p=head->next;
 while(p!=NULL)
 {
  if(p==NULL)
  printf("%d",p->data);
  else printf("%d ",p->data);
   p=p->next;
 }
}
int main()
{
 int n;
 struct node *head;
 scanf("%d",&n);
 head=creat(n);
 print(head);
 return 0;
}
0 0
原创粉丝点击