#include <stdio.h>
#include <stdlib.h>
/**
* 从键盘输入一个链表(整数,输入-1截止),排序后以二进制方式保存到文件a.bf中,然后从文件从读出,输出到屏幕上。
*/
struct Node{
int data;
struct Node *next;
};
void Insert(struct Node* L,int data){
struct Node* p = L;
//插入链表
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->next = L->next;
L->next = node;
L->data++; //链表的大小 +1
}
int main(){
int i,j,temp;
// 新建一个链表
struct Node* List = (struct Node*)malloc(sizeof(struct Node)),*p,*p1,*p3;
List->data = 0; //这里用来存链表的大小
Insert(List,56);
Insert(List,526);
Insert(List,156);
Insert(List,6);
Insert(List,786);
Insert(List,1);
printf("排序前:\n");
p3 = List->next;
while (p3!=NULL){
printf("%d ",p3->data);
p3 = p3->next;
}
printf("\n");
//对链表进行冒泡排序
p = List->next;
for(i=0;i<List->data-1;i++){
p1 = p;
for(j=0;j<List->data-1-i;j++){
if(p1->data < p1->next->data){
temp = p1->data;
p1->data = p1->next->data;
p1->next->data = temp;
}
p1 = p1->next;
}
}
printf("结果\n");
p3 = List->next;
while (p3!=NULL){
printf("%d ",p3->data);
p3 = p3->next;
}
return 0;
}
链表的冒泡排序算法
最新推荐文章于 2024-04-11 21:39:22 发布