# 單鏈結的泡沫排序法

### 1 個解答

• Wu
Lv 5
1 0 年前
最佳解答

typedef struct node_t

{ int num;

struct node_t *next;

} NODE;

void appendNode(NODE *node,int num)

{ NODE *ptr=node;

if (!node) return;

while (ptr->next) ptr=ptr->next;

if (ptr->next = (NODE *)calloc(sizeof(NODE),1))

ptr->next->num=num;

}

void deleteNode(NODE *node)

{ if (node)

{ deleteNode(node->next);

free(node);

}

}

int BubbleSort(NODE *node)

{ NODE *tmp;

if (node->next && node->next->next)

{ if (node->next->num > node->next->next->num)

{ tmp = node->next;

node->next = node->next->next;

tmp->next = node->next->next;

node->next->next = tmp;

return 1;

}

else return BubbleSort(node->next);

} else return 0;

}

void main()

{ int num, flag=1;

NODE root ={0,}, *ptr;

do

{ printf("input number:");

scanf("%d",&num);

if (num) appendNode(&root,num);

} while (num);

while (BubbleSort(&root));

printf("After Bubble Sort:");

for (ptr=root.next; ptr; ptr=ptr->next) printf("->%d",ptr->num);

printf("\n");

system("pause");

deleteNode(root.next);

}