我试图将一个节点附加到一个链表,但是,当我使用while循环来检查“链接”是否设置为NULL时,循环正在执行,而不应该执行。
就好像“cursor-> link”没有设置为NULL并且正在执行while循环中的代码一样,我把print语句放在那里只是为了测试它,即使“cursor-> link”也在执行它设置为NULL。 create函数返回“node *”。
编辑 - 我向大家道歉,我在深夜发布了这个问题,我想我可能不是最好的形式来正确地表达自己。另外,我仍然对如何处理和使用链接列表感到困惑(正如我的代码可能显示的那样)。我已经获得了一个可以使用的模板(如在函数追加和显示中预设,我将按原样使用它们)。编译器没有按原样引发任何警告。但是,程序仍然在While循环的附加函数中崩溃。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node {
int data;
struct node * link;
} node;
node* create(int data,node* link) {
node* newNode = (node*)malloc(sizeof(node));
newNode->data = data;
newNode->link = link;
return newNode;
}
void append ( node **, int ) ;
void display ( node * ) ;
int main() {
node *p ;
p=NULL;
int n;
char ch[10];
do {
printf("Enter the value\n");
scanf("%d",&n);
append(&p,n);
printf("Do you want to add another node? Type Yes/No\n");
scanf("%s",ch);
}while(!strcmp(ch,"Yes"));
printf("The elements in the linked list are");
display(p);
printf("\n");
return 0;
}
/* adds a node at the end of a linked list */
void append ( node **q, int num ){
node *cursor;
if (*q == NULL) {
*q = create(num, NULL);
node *cursor = *q;
}
while(cursor->link != NULL) {
printf("1\n");
cursor = cursor->link;
}
node* newNode = create(num, NULL);
cursor->link = newNode;
}
void display ( node *q ){
node *cursor = q;
while(cursor->link != NULL) {
printf(" %d", q->data);
cursor = cursor->link;
}
printf(" %d", cursor->data);
}
正如Ry所提到的,问题在于你在while循环中使用的光标,它从未被初始化。相反,当* q为null时,您将创建一个具有相同名称的新变量。我在你的代码中看到了另外一个问题,当list为空时,你要添加两个新节点。首先是空检查条件,然后是while循环。
要修复此行,请将“node * cursor = * q”移到外部,如果条件并添加返回。同时删除此行“node * cursor”
注意::我假设您的create方法没有问题。