链表排序代码
#include <iostream>
typedef struct node{
int data;
struct node *next;
}*LinkList,LNode;
void Init(LinkList &L)
{
L=(LinkList)malloc(sizeof(LNode));
L->next=NULL;
}
void Insert(LinkList &L,int m)
{
LinkList p,q;
p=(LinkList)malloc(sizeof(LNode));
p->data=m;
p->next=NULL;
q=L;
if(L==NULL)
{ L=p;
p->next=NULL;
}
else{
while (q->next!=NULL)
{
q=q->next;
}
q->next=p;
}
}
void Sort(LinkList &L)
{
LinkList p,q;
p=(LinkList)malloc(sizeof(LNode));
q=(LinkList)malloc(sizeof(LNode));
int h;
q=L->next;
while (q->next) {
p=q->next;
while (p) {
if(p->data<q->data)
{
h=p->data;
p->data=q->data;
q->data=h;
}
else {
p=p->next;
}
}
q=q->next;
}
}
void Print(LinkList &L)
{
LinkList p;
p=(LinkList)malloc(sizeof(LNode));
p=L->next;
while(p)
{ printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
int main(int argc, const char * argv[]) {
LinkList L;
int data,number;
Init(L);
Print(L);
scanf("%d",&number);
for(int i=0;i<number;i++)
{
scanf("%d",&data);
Insert(L,data);//1.尾插法,输入元素
}
Sort(L);
Print(L);
return 0;
}