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;
}
有序链表的插入
最新推荐文章于 2024-08-02 17:45:21 发布