SDUT 2874 师 链表的结点插入

在这里插入图片描述

#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
    int data;
    struct Node *next;
} node;
node *in(node *p,int x)//插入节点
{
    node *q;
    q=(node *)malloc(sizeof(node));
    q->data=x;
    q->next=NULL;
    q->next=p->next;
    p->next=q;
}
node *search(node *head,int m)//寻找插入点
{
    node *p;
    p=head;//如果p=head—>next; 会出错,因为没插入节点的链表的head的next为空
    while(m--&&p->next!=NULL)
            {
                p=p->next;
            }
    return p;
}
void output(node *head)//输出链表
{
    node *p;
    p=head->next;
    while (p!=NULL)
    {
        if (p->next==NULL)
            printf("%d\n",p->data);
        else
            printf("%d ",p->data);
        p=p->next;
    }
}
int main()
{
    node *head;
    int i,n,m,x;
    node *l;
    while(~scanf("%d",&n))
    {

        head=(node *)malloc(sizeof(node));
        head->next=NULL;
        for (i=0; i<n; i++)
        {
            scanf("%d %d",&m,&x);
            l=search(head,m);
            in(l,x);
        }
        output(head);
    }

    return 0;
}

ps:第一次独立完成链表的题,虽然只是最简单的插入,但还是有点激动,留念!

猜你喜欢

转载自blog.csdn.net/Here_SDUT/article/details/102940054