链表排序代码
#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; //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; }
还没有评论,来说两句吧...