我编译代码后,根本没有输出。
为什么链表末尾没有插入值10?
我认为在 p == NULL
之后,while 循环被退出,j->next
也会是 NULL
。因此,临时节点将被插入到链表的末尾。
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
}*first=NULL;
void Create(int array[],int size)
{
int i;
struct Node *temp,*last;
first = (struct Node*)malloc(sizeof(struct Node));
first->data = array[0];
first->next = NULL;
last = first;
for (i = 1 ; i < size ; i++){
temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = array[i];
temp->next = NULL;
last->next = temp;
last = temp;
}
}
void Print(struct Node *p)
{
while(p != NULL){
printf("%d ",p->data);
p = p->next;
}
}
void InsertingInSortedList(struct Node *p,int value)
{
struct Node *temp,*j = NULL;
temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = value ;
temp->next = NULL;
if(p == NULL){
first = temp;
}
else
{
while(p->data < value && p){
j = p;
p = p->next;
}
temp->next = j->next;
j->next = temp;
}
}
int main (void)
{
int b[] = {1,3,5,7,8,9};
int num = 6;
Create(b,num);
InsertingInSortedList(first,10);
Print(first);
return 0;
}