读书人

简单的链表为什么插入1 时候有异常

发布时间: 2013-03-25 15:43:04 作者: rapoo

简单的链表为什么插入1 时候有错误 ,别的时候正常
简单的链表为什么插入1 时候有异常 ,别的时候正常
简单的链表为什么插入1 时候有异常 ,别的时候正常
代码谢谢指导啊
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
using namespace std;
struct node {
int a;
node*next;
};
void sort1(node * head1,node *end1)
{
for(node*i=head1;i!=end1;i=i->next)
{

for(node*j=i->next;j!=NULL;j=j->next)
{
if(j->a>i->a)
{
int temp_swap=j->a;
j->a=i->a;
i->a=temp_swap;
}
}
}

}
void insert1(node*& head1,node* &end1)
{
cout<<"input the data to insert :";
node* insert_node=new node;
cin>>insert_node->a;
insert_node->next=NULL;

node *cur=head1;node*pre=head1;
if((insert_node->a)>=(head1->a))
{
insert_node->next=head1;
head1=insert_node;
}
else
{
while(((insert_node->a)<(cur->a))&&(cur!=NULL))//估计这有问题
{ pre=cur;
cur=cur->next;
cout<<"try";
}
if(cur==NULL)
{
pre->next=insert_node;
pre->next->next=NULL;
end1=pre->next;
}
else //估计到这有问题
{
insert_node->next=pre->next;
pre->next=insert_node;
cout<<"hahahahaha"<<endl;
}
}
}
void show_list(node*head1,node*end1)
{
node *temp=head1;
while(temp!=NULL)
{
cout<<temp->a<<" ";
temp=temp->next;


}
cout<<endl;
}
int main()
{
srand(time(NULL));
cout<<"input the size "<<endl;
int size;
cin>>size;
node *head=NULL;node *current=NULL;
for(int i=0;i<size;i++)
{
node *temp=new node;
cout<<"input the data :";
//cin>>temp->a;
temp->a=rand();
if(head==NULL)
{
head=temp;
current=temp;
}
else
{
current->next=temp;
current=current->next;
}

}
current->next=NULL;
cout<<"before sort "<<endl;
show_list(head,current);
cout<<"sort the list"<<endl;
sort1(head,current);
show_list(head,current);

insert1(head,current);
show_list(head,current);

cout << "Hello world!" << endl;
return 0;
}
[解决办法]
while(((insert_node->a)<(cur->a))&&(cur!=NULL))//估计这有问题
改为
while((cur!=NULL) && ((insert_node->a)<(cur->a)))
要先保证cur!=NULL后才能引用cur->a。

读书人网 >C++

热点推荐