链表插入

#include <stdio.h>
#include <stdlib.h>
//这里创建一个结构体用来表示链表的结点类型
struct node
    {
        int data;
        struct node *next;
    };
int main()
{
    struct node *head,*p,*q,*t;
    int i,n,m,a;
    scanf("%d",&n);
    head = NULL;
    for(i=1;i<=n;i++)
    {
        scanf("%d",&a);
        //建立
        p=(struct node *)malloc(sizeof(struct node));
        p->data=a;
        p->next=NULL;
        if(head==NULL)
            head=p;
        else
            q->next=p;
        q=p;
    }
        scanf("%d",&m);
    
    //插入
    t=head;
    while(t!=NULL)
    {
        if(t->next->data > m)
        {
            p=(struct node *)malloc(sizeof(struct node));
            p->data=m;
            p->next=t->next;
            t->next=p;
            break;
        }
        t=t->next;
    }
    
    t=head;//输出
    while(t!=NULL)
    {
        printf("%d ",t->data);
        t=t->next;
    }
    getchar();getchar();
    return 0;
}

 

posted @ 2016-11-16 17:11  LutyBKY  阅读(486)  评论(0编辑  收藏  举报