//输入n等于5
//连续输入5个数据 20 12 25 10 30
//从大到小排序后是 30 25 20 12 10
#include <stdio.h>
#include <stdlib.h>
struct linkNode
{
int data;
struct linkNode *next;
};
typedef struct linkNode *Link;
Link CreateLink(int n) //创建链表
{
Link head;
Link newNode,pNow;
int value;
int i;
head=NULL;
for(i=0;i<n;i++)
{
scanf("%d",&value);
newNode=(Link)malloc(sizeof(struct linkNode));
if(newNode==NULL)
{
printf("\n分配动态内存时出错.\n");
exit(1);
}
newNode->data = value;
newNode->next = NULL;
if(head==NULL)
{
head = newNode;
pNow = newNode;
}
else
{
pNow->next = newNode;
pNow = newNode;
}
}
return head;
}
void DispLink(Link p) //输出链表的所有节点
{
while(p)
{
printf("%d ",p->data);
p = p->next;
}
}
Link LinkSort(Link head) //选择排序法(从大到小)
{
Link p,other,maxNode;
int temp;
if(head == NULL) return head; //空链表
for(p = head; p->next != NULL; p = p->next)
{
maxNode=p;
for(other = p->next; other != NULL; other = other->next)
{
if(other->data > maxNode->data)
{
maxNode = other;
}
}
if(maxNode != p)
{
temp = p->data;
p->data = maxNode->data;
maxNode->data = temp;
}
}
return head;
}
int main()
{
Link head; //链表(不带头节点)
int n;
printf("输入链表的长度n: ");
scanf("%d",&n);
printf("连续输入%d个数据(以空格隔开): ",n);
head=CreateLink(n);
printf("\n原本链表的节点是: ");
DispLink(head);
LinkSort(head);
printf("\n从大到小排序之后: ");
DispLink(head);
printf("\n");
return 0;
}来自:求助得到的回答
温馨提示:答案为网友推荐,仅供参考