Description
建立长度为n的单链表,在第i个结点之前插入数据元素data。
Input
第一行为自然数n,表示链式线性表的长度;第二行为n个自然数表示链式线性表各元素值;第三行为指定插入的位置i;第四行为待插入数据元素data。
Output
指定插入位置合法时候,输出插入元素后的链式线性表的所有元素,元素之间用一个空格隔开。输入不合法,输出“error!”。
|  | 
#include<stdio.h>
#include<stdlib.h>
int total;
typedef struct node
{
    int data;
    struct node * next;
}Node;
void Create(Node*&L,int a[],int n)//尾插法
{
    Node *s,*r;
    int i;
    L=(Node*)malloc(sizeof(struct node));
    r=L;
    for(i=0;i<n;i++)
    {
        s=(Node*)malloc(sizeof(struct node));
        s->data=a[i];
        r->next=s;
        r=s;
    }
    r->next=NULL;
}
void input(Node*&L)//输入函数
{
    int a[1000];
    int i;
    scanf("%d",&total);
    for(i=0;i<total;i++)
    {
        scanf("%d",&a[i]);
    }
    Create(L,a,total);
}
bool Add(Node*L,int i,int e)//判断以及寻找要插入的位置
{
    if(i>total)
    {
        return false;
    }
    int j=0;
    Node *p,*q;
    p=L;
    while(j<i-1&&p)
    {
        j++;
        p=p->next;
    }
    if(p==NULL)
        return false;
    else
    {
        q=(Node*)malloc(sizeof(struct node));
        q->data=e;
        q->next=p->next;
        p->next=q;
        return true;
    }
}
 
void output(Node*L)//输出函数
{
    Node *read;
    read=L->next;
    while(read->next)
    {
        printf("%d ",read->data);
        read=read->next;
    }
    printf("%d",read->data);
}
int main()
{
    int i;
    Node*L;
    input(L);
    scanf("%d",&i);
    int e;
    scanf("%d",&e);
    if(Add(L,i,e))
    {
        output(L);
    }
    else
        printf("error!");
    return 0;
}
原文:http://www.cnblogs.com/FENGXUUEILIN/p/4397942.html