此代码应该在链表之后插入一个给定的 int,在链表之前插入一个给定的 int。但是,当我在 main 中传递参数时,它们不会将值存储在命令 insAfter 和 insBefore 中,而只是返回 0。我猜这与整数有关,但是当我让用户在实际中输入值时函数并将其设置为与“n”相同的值,并且它起作用了。
struct node {
int data;
char *item;
struct node* next;
};
struct node* root = NULL;
void insAfter();
void insBefore();
//Main
void main () {
}
//Command Insert After
void insAfter(int n) {
struct node* temp;
temp = (struct node*)malloc(sizeof(struct node));
n = temp->data;
temp->next = NULL;
if(root==NULL) {
root = temp;
printf("Text inserted at beginning\n");
}
else {
struct node* p;
p = root;
while(p->next != NULL) {
p = p->next;
}
p->next = temp;
printf("Ok\n");
}
}
//Command Insert Before
void insBefore(int n) {
struct node* temp;
temp = (struct node*)malloc(sizeof(struct node));
n = temp->data;
temp->next=NULL;
if (root == NULL) {
root = temp;
printf("Text inserted at beginning\n");
fflush(stdout);
}
else {
temp->next=root;
root = temp;
printf("Ok\n");
fflush(stdout) ;
}
}
最佳答案
ina()
和inb()
有一个小错误。
声明
n = temp->data;
应替换为
temp->data = n;
您不是将输入设置到列表,而是覆盖 n
,并且根本不修改列表节点的 data
。
关于C 链表节点不存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47115119/