您的位置:首页 > 其它

有序链表的插入

2017-12-02 22:21 232 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息