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 insert(NODE *p,int x) /*在链表的p结点位置后插入给定元素x*/
    33. {
    34. NODE *q;
    35. q=(NODE*)malloc(sizeof(NODE)); /*申请新的存储空间*/
    36. q->data=x;
    37. q->next=p->next; /*实现图2.9(b)的①*/
    38. p->next=q; /*实现图2.9(b)的②,将新结点q链接到p结点之后*/
    39. }
    40. main() /*主程序*/
    41. {
    42. int x,position; /*x为将插入的元素,position为插入位置的序号*/
    43. int i=0,j=0;
    44. NODE *c,*d;
    45. c=create(); /*建立单向链表*/
    46. d=c->next;
    47. while(d!=NULL) /*统计单向链表中结点数,置j中*/
    48. {
    49. d=d->next;
    50. j++;
    51. }
    52. d=c;
    53. do
    54. {
    55. printf("Input position (again):");
    56. scanf("%d",&position); /*position可为0,表示表头结点*/
    57. }while((position>j)||position<0); /*position值超过单向链表结点数,重新输入*/
    58. printf("Input x:");
    59. scanf("%d",&x);
    60. while(i!=position) /*由position值确定其在单向链表中的位置d*/
    61. {
    62. d=d->next;
    63. i++;
    64. }
    65. insert(d,x);
    66. printf("Output the list:");
    67. while(c->next!=NULL) /*输出插入x后的单向链表各元素*/
    68. {
    69. c=c->next;
    70. printf("%5d",c->data);
    71. }
    72. printf(" ok");
    73. }