c - 为什么节点没有插入到最后?
问题描述
编译代码后,根本没有输出。
为什么值 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;
}
解决方案
条件p->data < value && p
不对。在取消引用之前,您需要检查是否p
为 NULL 。p
正确的条件是p && p->data < value
。
谷歌c 短路评估以获取更多信息。
推荐阅读
- javascript - 在 Quasar (vue) 中使用解析从数据中获取数据 - 返回未定义
- javascript - 远程通知不会触发notificationclick
- docker - 如何在来宾操作系统和 Docker 容器之间绑定目录?
- php - Symfony 实体属性访问问题 无法确定访问类型
- vb.net - 如何将 PictureBox 中的图像保存到我的数据库中?
- php - CORS 错误:配置 Symfony 5 以接受 CORS 的正确方法是什么?
- python - 为 matplotlib Axes.scatter 指定颜色级别?
- php - 为什么 products.php 不影响 product.twig Opencart 3.0 中的任何更改?
- html - 如何控制模板中的边框,像这样?
- php - Laravel 8 - 路由不返回方法值