struct node
{
int num;
node *next;
};
/*按照从小到大的顺序插入节点p,返回头节点*/
node* insertNode(node *head,node *p)
{
if(p->num<head->num)
{
p->next=head;
return p;
}
insertNode(head->next,p);
return head;
}
/*单链表插入排序*/
node* insertSort(node * head)
{
for(node *pCur=head;pCur->next;)
{
/*只能从前往后插*/
if(pCur->num>pCur->next->num)
{
node *pNext=pCur->next;
pCur->next=pCur->next->next;
head=insertNode(head,pNext);
}
else
{
pCur=pCur->next;
}
}
return head;
}
/*单链表选择排序*/
node * selectSort(node *head)
{
node * tmp=new node;
tmp->next=head;
head=tmp;
node *pCur;//用于遍历链表的指针
node *pPreMin;//指向当前链表最小值节点的前一个节点
node*pMin;//指向当前链表最小值节点
node *rhead=NULL;
while(head->next)
{
for(pCur=head,pPreMin=pCur;pCur->next;pCur=pCur->next)
{
if(pPreMin->next->num>pCur->next->num)
pPreMin=pCur;
}
pMin=pPreMin->next;
pPreMin->next=pMin->next;
pMin->next=rhead;
rhead=pMin;
}
delete head;
return rhead;
}
/*单链表冒泡排序*/
void bubbleSort(node **head)
{
node * tmp=new node;
tmp->next=*head;
*head=tmp;
node *end=NULL;
node *pPre,*pCur;
while((*head)->next!=end)
{
for(pPre=*head,pCur=pPre->next;pCur->next!=end;)
{
if(pCur->num>pCur->next->num)
{
/*交换pCur和pCur->next的位置*/
pPre->next=pCur->next;
pCur->next=pPre->next->next;
pPre->next->next=pCur;
}
pPre=pPre->next;
pCur=pPre->next;
}
end=pCur;
}
*head=(*head)->next;
delete tmp;
}
/*测试程序*/
node * createNode(int *num,int len)
{
node * head=new node[len];
node *p=head;
for(int i=0;i<len;i++)
{
p->num=num[i];
p->next=p+1;
p++;
}
(--p)->next=NULL;
return head;
}
void main()
{
int num[]={10,9,87,6,5,4,3,2,1,109};
node *head=createNode(num,10);
head=selectSort(head);
head=insertSort(head);
bubbleSort(&head);
while(head)
{
cout<<head->num<<endl;
head=head->next;
}
system("pause");
}