各位大神好,
最近在学习C语言。
想要用linked-list写bubble sort
这是我参考网络上的做法,最后有成功排序的程式码
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void printLinkedList(struct node *start);
void swap(struct node *node1, struct node *node2);
void bubbleSort(struct node *start);
// ================================================
int main()
{
int arry[10];
struct node *prev, *first = NULL, *current;
printf("Please type in the 01st number:");
scanf("%d", &arry[0]);
printf("Please type in the 02nd number:");
scanf("%d", &arry[1]);
printf("Please type in the 03rd number:");
scanf("%d", &arry[2]);
printf("Please type in the 04th number:");
scanf("%d", &arry[3]);
printf("Please type in the 05th number:");
scanf("%d", &arry[4]);
printf("Please type in the 06th number:");
scanf("%d", &arry[5]);
printf("Please type in the 07th number:");
scanf("%d", &arry[6]);
printf("Please type in the 08th number:");
scanf("%d", &arry[7]);
printf("Please type in the 09th number:");
scanf("%d", &arry[8]);
printf("Please type in the 10th number:");
scanf("%d", &arry[9]);
int i;
for (i = 0; i < 10; i++)
{
current = (struct node*)malloc(sizeof(struct node));
current -> data = arry[i];
if (i == 0)
{
first = current;
}
else
{
prev -> next = current;
}
current -> next = NULL;
prev = current;
}
printf("\n");
printf("List before sorting:");
printLinkedList(first);
printf("\n");
bubbleSort(first);
printf("List after sorting:");
printLinkedList(first);
printf("\n\n");
return 0;
}
// ================================================
void printLinkedList(struct node *start)
{
struct node *tmp = start;
while(tmp != NULL)
{
printf("%d,", tmp -> data);
tmp = tmp -> next;
}
}
//