师--链表的结点插入

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node*next;
};
struct node *head;
int len;
void print(struct node * head)
{
    struct node *p;
    p=head->next;
    while(p!=NULL)
    {
        printf("%d",p->data);
        if(p->next!=NULL)
        {
            printf(" ");
        }
        else
        {
            printf("\n");
        }
        p=p->next;
    }

}
void insert(int mi,int xi)
{
    struct node *p,*q;
    int i;
    p=head;
    for(i=1; i<=mi&&i<=len; i++)
    {
        p=p->next;
    }
    q=(struct node *)malloc(sizeof(struct node));
    q->data=xi;
    q->next=NULL;
    q->next=p->next;
    p->next=q;
    len++;
}


int main()
{
    int n,i,xi,mi;

    while(scanf("%d",&n)!=EOF)
    {
        head=(struct node *)malloc(sizeof(struct node));
        head->next=NULL;
        len=0;
        for(i=1; i<=n; i++)
        {

            scanf("%d %d",&mi,&xi);
            insert(mi,xi);
        }
        print(head);

    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41341757/article/details/81746258