#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int data;
struct Node *next;
}node;
//单链表排序,比较过程中只交换节点数据
void link_sort(node *head)
{
node *tmp1 = head->next;
node *tmp2 = NULL;
int val = 0;
if(tmp1 == NULL)
return;
for(tmp1 = head->next; tmp1->next != NULL; tmp1 = tmp1->next){
for(tmp2 = tmp1->next; tmp2 != NULL; tmp2 = tmp2->next){
if(tmp1->data > tmp2->data){
val = tmp1->data;
tmp1->data = tmp2->data;
tmp2->data = val;
}
}
}
}
void link_init(node *head)
{
head->next = NULL;
}
void link_delete(node *head)
{
node *tmp = NULL;
while(head->next){
tmp = head->next;
head->next = tmp->next;
free(tmp);
tmp = NULL;
}
}
int link_add_head(node *head, int val)
{
node *new = NULL;
new = (node *)malloc(sizeof(node));
if(!new)
return 0;
new->data = val;
new->next = head->next;
head->next = new;
return 1;
}
int main()
{
node head = {0};
node *tmp = NULL;
link_init(&head);
link_add_head(&head, 7);
link_add_head(&head, 6);
link_add_head(&head, 3);
link_add_head(&head, 9);
link_add_head(&head, 8);
link_add_head(&head, 5);
link_add_head(&head, 4);
link_add_head(&head, 2);
link_sort(&head);
tmp = head.next;
while(tmp){
printf("%d ", tmp->data);
tmp = tmp->next;
}
printf("\n");
link_delete(&head);
return 0;
}
单链表排序
最新推荐文章于 2021-04-14 00:43:27 发布