代码自己实现过一遍就是有更加深入的理解:
node* insert_sort()
{
int data = 0;
int i = 0;
node *head, *Cur, *Pre, *New;
head = (node*)malloc(sizeof(node));
while(1)
{
printf("Please input the data: ");
scanf("%d", &data);
if(data == 0)
break;
New = (struct node*)malloc(sizeof(struct node));
Pre = (struct node*)malloc(sizeof(struct node));
Cur = (struct node*)malloc(sizeof(struct node));
New->data = data; // 新分配一个node节点
New->next = NULL;
if(++i == 1)
{
head->next = New;
continue;
}
if(head->next->data >= New->data)
{
New->next = head->next;
head->next = New;
continue;
}
Cur = head->next;
while(New->data > Cur->data && Cur->next != NULL)
{
Pre = Cur;
Cur = Cur->next;
}
if(Cur->data >= New->data)
{
Pre->next = New;
New->next = Cur;
}
else
{
Cur->next = New;
}
}
return head;
}
上文中head节点初始化,其他节点的初始化是很重要的问题。
未初始化很容易出现debug版本没问题,而release版本不通过的现象。
同时注意到head节点是空节点,并不是头结点,所以要小心处理有关head节点的情况