链表 (已排好序 插入一个元素仍有序)

#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
    int date;
    struct node *next;
}lnode;
void creatlist(lnode *h,int n)//尾插法创建链表
{
    lnode *p,*r;
    int i,x;
    r=h;
    for(i=0;i<n;i++)
    {
        scanf("%d",&x);
        p=(lnode *)malloc(sizeof(lnode));
        p->date=x;
        r->next=p;
        r=p;
    }
    r->next=NULL;
}
void insert(lnode *h,int x)
{
    lnode *p,*pre,*q;
    pre=h;
    p=pre->next;
    while(p!=NULL&&p->date<x)
    {
        pre=p;
        p=p->next;
    }
    q=(lnode*)malloc(sizeof(lnode));
    pre->next=q;
    q->date=x;
    q->next=p;
}
void outputlist(lnode *h)
{
    lnode *p;
    p=h->next;
    while(p!=NULL)
    {
        printf("%d ",p->date);
        p=p->next;
    }
    printf("\n");
}
int main()
{
    int n,x;
    lnode *h;
    h=(lnode *)malloc(sizeof(lnode));
    h->next=NULL;
    while(scanf("%d",&n)!=-1)
    {
        creatlist(h,n);
        scanf("%d",&x);
        insert(h,x);
        outputlist(h);
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/xqx1343002589/article/details/80405439