#include<stdio.h>
#include<malloc.h>
typedef int ElemType;
typedef struct Node
{
ElemType data;
struct Node *next;
/* data */
}Node,*LinkList;
//头插法
void head_creat_list(LinkList *p, int n){
//n是容量
*p = (Node *)malloc(sizeof(Node));
(*p)->next = NULL;
int i;
for(i=1; i<=n; ++i){
Node *q = (Node *)malloc(sizeof(Node));
scanf("%d",&q->data);
q->next = (*p)->next;
(*p)->next = q;
}
}
void insert_sort(LinkList *p, LinkList *new){
//创建新链表头结点
*new = (Node *)malloc(sizeof(Node));
(*new)->next = NULL;
Node *q = (*p)->next;
while(q){
Node *loc,*pre;
loc = (*new)->next;
if((*new)->next == NULL || loc->data > q->data){
Node *s =(Node *)malloc(sizeof(Node));
s->data = q->data;
s->next = (*new)->next;
(*new)->next = s;
}
else{
pre = loc->next;
//loc指向当前节点
//pre指向后一个节点
while (pre && pre->data < q->data)
{
loc = pre;
pre = pre->next;
}
Node *s =(Node *)malloc(sizeof(Node));
s->data = q->data;
s->next = pre;
loc->next = s;
}
q = q->next;
}
}
void show(LinkList *p){
//第一个数据节点
Node *q = (*p)->next;
while(q){
printf("%3d",q->data);
q = q->next;
}
printf("\n");
}
int main(){
LinkList list1;
LinkList list2;
head_creat_list(&list1,6);
printf("排序前:");
show(&list1);
insert_sort(&list1,&list2);
printf("排序后:");
show(&list2);
return 0;
}
链式存储的直接插入排序
最新推荐文章于 2022-12-06 15:56:33 发布