有一个单链表,其data成员存放整数,第一个节点的指针为head,编写一个程序,将元素总小到大排序,并输出节点,采用冒泡排序
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node *next;
}*Node;
Node create()
{
Node p,q,head;
head = (Node)malloc(sizeof(struct node));
head->next=NULL;
p=head;
int i,n;
printf("请输入创建的单链表节点的个数:\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
q=(Node)malloc(sizeof(struct node));
printf("请输入节点信息data:\n");
scanf("%d",&q->data);
q->next =NULL;
p->next =q;
p = q;
}
return head;
}
void print(Node head)
{
Node p=head->next;
while(p)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
void Sort(Node head)
{
Node q,p,pre,end=NULL;
pre = head;
p=head->next;
q = p->next;
int i,num=0;
while(p)
{
num++;
p = p->next;
}
for(i=0;i<num-1;i++)
{
pre = head;
p=head->next;
q = p->next;
while(q!=end)
{
if(p->data>q->data)
{
p->next = q->next;
q->next = p;
pre->next=q;
}
pre=pre->next;
p=pre->next;
q=p->next;
}
end=p;
}
printf("排序完成!\n");
}
int main()
{
Node head=NULL;
head = create();
printf("排序前:\n");
print(head);
Sort(head);
printf("排序后:\n");
print(head);
}
//4 5 6 9 3 2 1 8 7 10