【发布时间】:2014-02-22 00:35:07
【问题描述】:
我试图在 C 中递归地实现一个插入函数,但我遇到了各种各样的问题。我正在上 CS 入门课程,他们在我们以前接触过 C 实验室之前就开始向我们扔 C 实验室。部分问题是列表指针未被识别为 NULL,我也很确定我使用 malloc 不正确。
#include <stdio.h>
#include <stdlib.h>
#define True 1
#define False 0
typedef int BOOLEAN;
struct Node{
int value;
struct Node *next;
};
void insert(int x, struct Node **pL){
printf("insert\n");
if(*pL == NULL){
printf("inside if\n");
struct Node *pN;
pN = (struct Node*) malloc(sizeof(struct Node));
(*pN).value = x;
(*pN).next = NULL;
return;
}
if (*pL != NULL){
printf("inside else\n");
insert(x, &(((*pL)->next)));
}
printf("end insert\n");
};
void printList(struct Node *L){
while (L != NULL){
printf("%d", (*L).value);
printList((*L).next);
}
return;
};
main(){
printf("main\n");
struct Node* L;
//L).next = NULL;
int i;
printf("for loop\n");
for (i = 3; i < 20; i+=2){
printf("%d\n", i);
insert(i, &L);
}
printList(L);
};
【问题讨论】:
-
struct Node* L = NULL;可能会修复一些问题 -
我已经尝试过了,它只是延迟了不可避免的问题。由于它会递归调用它,最终它会到达需要检查 NULL 的地步,一切都下地狱了。
-
(为了节省我们阅读所有内容的时间)问题到底出在哪里?哪个功能?
-
插入函数,第一个if语句
-
哦,我明白了——你创建了 pn,但没有把它放在列表中
标签: c insert null linked-list