这是我写的关于链表排序的问题,我想用的是冒泡排序法,但我不会求节点个数,就默认五个吧,但系统还是会停止工作 = =
#include<iostream.h>struct student
{
long int number;
char *name;
int sex;
int age;
student* next;
};
student* head = NULL;
student* newhead = NULL;
void Create();
void sort();
void main()
{
student* pS;
Create( );
cout<<"您输入的链表是:"<<endl;
pS = head;
for( ; pS; pS=pS->next )
cout<<pS->number<<" "<<pS->name<<" "<<pS->sex<<" "<<pS->age<<endl;
cout<<endl;
sort();
pS = newhead;
for( ; pS; pS=pS->next )
cout<<pS->number<<" "<<pS->name<<" "<<pS->sex<<" "<<pS->age<<endl;
cout<<endl;
}
void Create()
{
student* pS = NULL;
student* pEnd = NULL;
cout<<"请顺次输入学生的学号,姓名,性别和年龄:"<<endl;
pEnd = pS = new student;
pS->name = new char [10];
cin>>pS->number>>pS->name>>pS->sex>>pS->age;
while( pS->number != 0 )
{
if( head == NULL )
{
head = pS;
}
else
pEnd->next = pS;
pEnd = pS;
pS = new student;
pS->name = new char [10];
cin>>pS->number>>pS->name>>pS->sex>>pS->age;
}
pEnd->next = NULL;
delete pS;
}
void sort( )
{
int i = 0 , pass , l = 0;
student* pS = head;
student* ptr = NULL;
student* temp = NULL;
for( pass=1; pass<5; pass++ )
{
pS = head + l;
for( ; pS; pS = pS->next )
{
if( pS->number > pS->next->number )
{
temp = pS->next;
pS->next = pS->next->next;
if( ptr==NULL )
{
temp->next = pS;
pS = temp;
}
else
{
temp->next = pS;
ptr->next = temp;
pS = temp;
}
ptr = pS;
}
}
l++;
}
}