请教:单链表的排序
编了一个类似于插入法的排序,我的思路是:一边建立链表,一边进行插入排序;但总出错,调试了几次,发现可能是for循环出错了(红字标出),请教各位高手帮忙看看!#include <stdio.h>
#include <stdlib.h>
void Printflink(struct Node* head); //输出链表
#define TRUE 1
struct Node
{
int data;
struct Node* next;
};
int main()
{
int iData = 0;
struct Node* head = NULL;
struct Node* pCurrent = NULL;
struct Node* pNewNode = NULL;
struct Node* pForward = NULL;
while (TRUE)
{
scanf("%d",&iData);
if (iData == 0)
{
break;
}
pNewNode = malloc(sizeof(struct Node));
pNewNode->data = iData;
pNewNode->next = NULL;
if (head == NULL) //链表为空
{
head = pNewNode;
continue;
}
if (pNewNode->data <= head->data) //表头交换
{
pNewNode->next = head;
head = pNewNode;
continue;
}
for (pCurrent=head->next,pForward=head; pCurrent!=NULL; pCurrent=pCurrent->next,pForward=pForward->next)
{
if (pNewNode->data < pCurrent->data)
{
pForward->next = pNewNode;
pNewNode->next = pCurrent;
break;
}
}
if (pCurrent == NULL)
{
pCurrent = pNewNode;
}
}
Printflink(head);
return 0;
}
void Printflink(struct Node* head)
{
struct Node* pTemp = NULL;
if (head == NULL)
{
printf("Link is empty!\n");
return;
}
else
{
for (pTemp=head; pTemp!=NULL; pTemp=pTemp->next)
{
printf("%d\n",pTemp->data);
}
}
}