对单链表的排序(选择排序)
思路就是每次把最小值放在最后一个。
比如除头结点的五个5个节点;
开始每个节点分别赋值为 5,3,1,4,2;
第一次外循环后结果变为 5,3,4,2,1;
第二次外循环后结果变为 5,3,4,1,2;
第三次外循环后结果变为 5,4,1,2,3;
第四次外循环后结果变为 5,1,2,3,4;
第五次外循环后结果变为 1,2,3,4,5;
/*节点结构体*/
typedef struct Node//定义单链表节点
{
int date;
Node *next;
}Node;
/*一个有头链表的排序问题*/
void SortList(Node *pHead)//传来一个头节点指针
{
Node *q,*tail=pHead->next,*t;
while(tail->next!=NULL)
{
tail=tail->next;//找到尾巴
}
int min,i,j;
for(i=0;i<ListLength(pHead);i++)//ListLength(pHead)为单链表长度(不包括头节点) 的函数
{
q=pHead;
t=q;
min=q->next->date;
for(j=0;j<ListLength(pHead)-i;j++)
{
if(min > q->next->date)//找到最小值,用 t 记录最小值节点上一个节点
{
min=q->next->date;
t=q;
}
q=q->next;
}
if(tail==t->next)//如果最小值节点为尾节点,无需调换
{
continue;
}
else
{
tail->next=t->next;
t->next=t->next->next;
tail=tail->next;
tail->next=NULL;
}
printList(pHead);//打印链表函数
}
cout<<"!!排序完成!!\n";
}
排序用到的ListLength函数以及printList函数
int ListLength(Node *pHead)
{
int size=0;
while(pHead->next!= NULL)
{
size++;
pHead = pHead->next;
}
return size;
}
void printList(Node *pHead)
{
if(pHead->next==NULL)
{
cout<<"打印链表。。。链表为空。。。\n";
}
else
{
cout<<"。。。打印链表 。。。\n";
while(pHead->next!=NULL)
{
cout<<pHead->next->date<<" ";
pHead=pHead->next;
}
cout<<endl;
}
}