c++链表排序问题

2025-04-24 09:43:14
推荐回答(1个)
回答1:

#include
#include
#include
#include
using std::cin;
using std::cout;
using std::endl;
struct node {  char c ;   node *next  ;  };

node *  create( )
{
node *head=0;
node *p,*tail;

while (true)
{
p=new node;
p->c=rand()%26+65;
p->next=0;
if(head==0)
{
head=p;
tail=p;
}
else
{
tail->next=p;
tail=tail->next;
}
if(p->c=='M') 
break;
}
return head;
}

void  print (  node  *head  )
{
node*p=head;
while(p)
{
cout.width(4);
cout<c;
p=p->next;
}
cout<}

void  free (  node  *head  )
{
node*p;
while(head)
{
p=head;
head=head->next;
delete p;
}
}


node *  sort (  node  *head  )
{
//循环初始化应该放外边;
node *h=0; 
node *temp=head;
head=head->next;//head指向未排序的头
temp ->next = 0;
h=temp;//h指向排过序的头
while(head)
{
temp=head;//取一个未排序的元素
head=head->next;//始终指向未排序的头
/*if(h==0)
{
h=temp;
temp->next=0;
continue;
}

if(h->c >= temp->c)//判断插入的位置是否是已排序链表的表头处
{
temp->next =  h;
h = temp ;
cout<<"我进来了"< continue ;
}
*/
node *p1,*p2;
p1=p2=h;
if(h->c>=temp->c)
{
temp->next=h;
h=temp;
}
else
{
while(temp->c > p2->c && p2->next!=0)//找到插入的位置
{
p1=p2;
p2=p2->next; 
}
if(temp->c <= p2->c)
{
temp->next=p2;
p1->next=temp;
}
else
{
p2->next  = temp ;
temp ->next = 0 ;
}
}
}
return h;
}


void main ()
{
time_t* t=0;
srand(time(t));
node *head;
head=create( );
print (  head  );
head=sort ( head  );//排完序,头已经改变了
print (  head  );
free( head );
}

主要是排序函数有问题,其他的主要是我用的编译器可能和你的不同

我改的主要有:

1、循环的初始化部分一般放在外边,这样就不用每次在循环里判断

2、循环的判断条件必须更新

3、原程序的排序本质上是插入法排序,我改后依旧是插入法排序,由于插入法排序之后,链表头指针已经变了,所以sort函数返回新的链表头指针,这个主函数中要更新head,

4、排序函数中最容易忽略的是当要插入的元素的位置是链表头时,这时候要改变链表头h