使用链表的方法进行冒泡排序

来源:互联网 发布:数据挖掘32个经典案例 编辑:程序博客网 时间:2024/06/05 06:02
#include <stdio.h>#include <stdlib.h>#include <malloc.h>typedef struct node{int data;//int mem[100000000];struct node *next;}Node;// 将数组a中的num个元素顺序放到以pHead为头结点的列表中void arrayToList(int a[],int num, Node *pHead){if(0 != num){pHead->data = a[0];}Node *pCurr = pHead;for(int i = 1; i < num; ++i){Node *temp = (Node *)malloc(sizeof(node));temp->data = a[i];temp->next = NULL;pCurr->next = temp;pCurr = pCurr->next;}}// 输出链表中所有结点void printAllNode(Node *pHead){while(NULL != pHead){printf("%d\t",pHead->data);pHead = pHead->next;};printf("\n");}// 使用冒泡排序法对以pHead为头的链表进行排序void listBuubleSort(Node *pHead){for(Node *pi = pHead; pi != NULL; pi = pi->next){for(Node *pj = pi->next; pj != NULL; pj = pj->next){if(pi->data > pj->data){int temp = pj->data;pj->data = pi->data;pi->data = temp;}}}}// 删除链表void releaseNodes(Node *pHead){while(NULL != pHead){//printf("%d\n",pHead->data);Node *tmp = pHead;pHead = pHead->next;if(NULL != tmp){free(tmp);}};}int main(void){int a[10] = {2,7,8,3,5,1,0,6,9,4};Node *pHead = (Node *)malloc(sizeof(Node));pHead->next = NULL;arrayToList(a,10,pHead);printAllNode(pHead);listBuubleSort(pHead);printAllNode(pHead);releaseNodes(pHead);    getchar();return 0;}


 

原创粉丝点击