代码对不对,跑一下就清楚了
程序代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
}Linknode, *Link;
void Insertsort(Link L)
{
Link p, q, r, u;
p = L->next; L->next = NULL;//置空表
while (p != NULL)
{
r = L;
q = L->next;
while (q != p && q->data <= p->data)
{
r = q;q = q->next;//q=L,而L已经被置空表了,上面说L->next=NULL;q->next不是为空了吗??
}
u = p->next;
p->next = r->next;
r->next = p;
p = u;
}
}
Link CreateLink(int *array, size_t size)
{
// 创建带头节点链表
Link head = calloc(1, sizeof(Linknode));
Link p = head;
for (size_t i = 0;i < size;i++)
{
Link s = calloc(1, sizeof(Linknode));
s->data = *(array + i);
// 尾插法
p->next = s;
p = s;
}
return head;
}
void Destory(Link l)
{
if (l) Destory(l->next);
free(l);
}
void PrintLink(Link l)
{
Link p = l;
while (p = p->next)
{
printf("%3d", p->data);
}
printf("\n");
}
int main(int argc, char *argv[])
{
int sa[] = {2, 5, 7, 3};
Link link = CreateLink(sa, sizeof(sa) / sizeof(int));
PrintLink(link);
Insertsort(link);
PrintLink(link);
Destory(link);
return 0;
}