有序链表的插入

来源:互联网 发布:2017网络综艺节目排名 编辑:程序博客网 时间:2024/05/17 21:51
struct node{    int data;    node* next;};node head;int len;node* creat(){    head.next=0;    node* r=&head;    r->next=NULL;    node* p;    int data;    for( int i=0;i<len;i++)    {        cin>>data;        p=new node;        p->data=data;        p->next=r->next;        r->next=p;        r=p;    }    return &head;}void insert( const int& data)//有序递增链表要插入的数据data{    node* pre=&head;    node* cur=head.next;    while(cur)    {        if(cur->data>data)            break;        else        {            pre=cur;            cur=cur->next;        }    }    node* obj=new node;    obj->data=data;    pre->next=obj;    obj->next=cur;}void show(){    node* p=head.next;    while(p)    {        cout<<p->data;        if(p->next)            cout<<' ';        p=p->next;    }    cout<<endl;}void discard(){    node* p=head.next;    while(p)    {        node* q=p;        p=p->next;        delete q;    }}int main(){    int data;   while(cin>>len>>data)   {       creat();       insert(data);       show();       discard();   }    return 0;}