这是我的代码。它不起作用:
void insertioon (int d) // this part, insert and sort list
{
struct node *np, *temp, *prev;
int found;
np=malloc(sizeof(struct node));
np->data = d;
np->nextPtr = NULL;
temp=firstPtr;
found=0;
while ((temp != NULL) && !found)
{
if (temp->data <d)
{
prev = temp;
temp = temp->nextPtr;
}
else
{
found=1;
}
if (prev == NULL)
{
np->nextPtr=firstPtr;
firstPtr=np;
}
else
{
prev->nextPtr = np;
np->nextPtr = temp;
}
}
}
我的错误是什么?在insertioon中,我想对此列表进行排序。
答案 0 :(得分:0)
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *nextPtr;
};
struct node *firstPtr = NULL;
void insertioon (int d){
struct node *np, *temp, *prev = NULL;
int found;
np=malloc(sizeof(struct node));
np->data = d;
np->nextPtr = NULL;
temp=firstPtr;
found=0;
while ((temp != NULL) && !found)
{
if (temp->data <d)
{
prev = temp;
temp = temp->nextPtr;
}
else
{
found=1;
}
}
if (prev == NULL)
{
np->nextPtr=firstPtr;
firstPtr=np;
}
else
{
prev->nextPtr = np;
np->nextPtr = temp;
}
}
void print_list(struct node *np){
while(np){
printf("%d ", np->data);
np=np->nextPtr;
}
}
int main(){
insertioon(10);
insertioon(5);
insertioon(7);
insertioon(1);
insertioon(16);
print_list(firstPtr);//1 5 7 10 16
printf("\n");
return 0;
}