12、主函数定义并初始化一个链表(长度为6),通过键盘录入每个结点的数据,并先遍历输出链表。在子函数LinkBubbleSort(LinkList head)中实现链表的冒泡排序,从大到小,遍历输出在控制台上。
时间: 2024-05-27 19:11:22 浏览: 33
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int data;
struct Node *next;
}Node, *LinkList;
LinkList createList(int n){
LinkList head = (LinkList)malloc(sizeof(Node));
head->next = NULL;
LinkList p = head;
for(int i=0; i<n; i++){
LinkList node = (LinkList)malloc(sizeof(Node));
scanf("%d", &node->data);
node->next = NULL;
p->next = node;
p = p->next;
}
return head;
}
void printList(LinkList head){
LinkList p = head->next;
while(p){
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void LinkBubbleSort(LinkList head){
LinkList p = head->next;
int len = 0;
while(p){
len++;
p = p->next;
}
for(int i=0; i<len-1; i++){
p = head->next;
for(int j=0; j<len-1-i; j++){
if(p->data < p->next->data){
int temp = p->data;
p->data = p->next->data;
p->next->data = temp;
}
p = p->next;
}
}
}
int main(){
LinkList head = createList(6);
printList(head);
LinkBubbleSort(head);
printList(head);
return 0;
}
阅读全文