1. #include<stdio.h>
    2. #include<malloc.h>
    3. typedef struct node /*定义结点的存储结构*/
    4. {
    5. int data;
    6. struct node *next;
    7. }NODE;
    8. NODE *create() /*此函数采用后插入方式建立单链表,并返回一个指向链表表头的指针*/
    9. {
    10. NODE *head,*q,*p; /*定义指针变量*/
    11. int a,n;
    12. head=(NODE*)malloc(sizeof(NODE)); /*申请新的存储空间,建立表头结点*/
    13. q=head;
    14. printf("\nInput number of the list: ");
    15. scanf("%d",&n); /*输入单向链表结点个数*/
    16. if(n>0) /*若n<=0,建立仅含表头结点的空表*/
    17. {
    18. printf("Input the list :");
    19. while(n>0)
    20. {
    21. scanf("%d",&a); /*输入新元素*/
    22. p=(NODE*)malloc(sizeof(NODE));
    23. p->data=a;
    24. q->next=p;
    25. q=p;
    26. n--;
    27. }
    28. }
    29. q->next=NULL;
    30. return(head); /*返回表头指针head*/
    31. }
    32. void print(NODE *head) /*输出单向链表各元素,第3章中也用到此函数*/
    33. {
    34. NODE *p;
    35. p=head->next;
    36. printf("Output the list:");
    37. while(p!=NULL)
    38. {
    39. printf("%3d",p->data);
    40. p=p->next;
    41. }
    42. }
    43. main()
    44. {
    45. NODE *a;
    46. a=create();
    47. print(a);
    48. }