自己写的的一个链表排序,针对的是一个无序的链表。基本思路是将旧链表的节点一个一个分离并按顺序插入另一个链表,然后将就链表表头指向新链表。
#include<stdio.h>
typedef struct node Node;
struct node
{
int num;
Node *next;
};
//生成一个新节点
Node *creat_node(void)
{
Node *new_node = (Node *)malloc(sizeof(Node));
if(new_node == NULL)
{
printf("malloc error !\n");
exit(1);
}
new_node->next = NULL;
return(new_node);
}
//表头初始化
void init_head(Node **head){
(*head) = creat_node();
}
//打印链表信息
void list_print(Node **head)
{
Node *temp = (*head)->next;
while(temp != NULL)
{
printf("%d\n",temp->num);
temp = temp->next;
}
}
//头插法
void head_insret(Node **head,Node **new)
{
(*new)->next = (*head)->next;
(*head)->next = (*new);
}
尾插法
void tail_insret(Node **head,Node **new)
{
Node *temp = (*head);
while(temp->next != NULL)
{
temp = temp->next;
}
temp->next = (*new);
}
//对链表排序
void list_sort(Node **head)
{
Node *ptr;
Node *plast;//上一个节点
Node *pnext;//下一个节点
Node *temp = creat_node(); //新链表的临时表头
while((*head)->next != NULL) //依次取旧表表头下一个节点(该节点存在)
{
plast = temp;
pnext = temp->next;
ptr = (*head)->next->next;
while(pnext != NULL && (*head)->next->num >= pnext->num)//在新表中找到插入点
{
plast = pnext;
pnext = pnext->next;
}
plast->next = (*head)->next;
(*head)->next->next = pnext;
(*head)->next = ptr;
if((*head)->next == NULL)
{
(*head) = temp;//旧表头指向新表头
break;
}
}
free(temp);
}
int main(int argc, char **argv)
{
Node *head;
Node *new;
init_head(&head);
srand((unsigned int)time(0));
int i ;
for(i = 1; i <= 100; i++)
{
new = creat_node();
new->num = rand() % 100;
head_insret(&head,&new);
}
list_print(&head);
printf("\n");
list_sort(&head);
list_print(&head);
return(0);
}
如果可以,尽量在建立链表的时候每个节点就按照顺序插入链表中。这样就可以免去后面排序的工作。