逆序建立链表

来源:互联网 发布:java colortorgb 编辑:程序博客网 时间:2024/04/30 18:13

#include<stdio.h>
#include<malloc.h>
struct node
{
 int data;
 struct node *next;
};
struct node *creat(int n)
{
 struct node *head,*tail,*p;
 head=(struct node *)malloc(sizeof(struct node));
 head->next=NULL;
 
 int i;
 for(i=0;i<n;i++)
 {
  p=(struct node *)malloc(sizeof(struct node));
  scanf("%d",&p->data);
  p->next=head->next;
  head->next=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);
 printf("\n");
 return 0;
}
0 0
原创粉丝点击