gpt4 book ai didi

C 链表插入和显示功能不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 08:23:41 26 4
gpt4 key购买 nike

我正在尝试实现一个链表。但不幸的是它不起作用。我已经尝试更改代码。它不起作用。插入功能不起作用,而且当我调用 displaylist() 函数时我也没有看到任何东西。请帮帮我。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct node {
int key;
struct node *next;
} node;

struct node *head, *z, *t;

listinit(void)
{
head = (struct node *) malloc(sizeof *head);
z = (struct node *) malloc(sizeof *z);
head->next = z;
z->next = z;
}

delnext(struct node *t)
{
t->next = t->next->next;
}

node *insertafter(int v, struct node *t)
{

struct node *x;
x = (struct node *)malloc(sizeof *x);
x->key = v;
x->next = t->next;
t->next = x;
return x;
};

void displaylist(void)
{
node *curr = head->next;
while(curr != z){
printf("%d -> ", curr->key);
curr = curr->next;
}
printf("\nHappy Coding! :D\n\n");
}

int main(void)
{
listinit();
int cmd = 0,val = 0;
printf("MENU: \n"
"1. INSERT\n"
"2. DELETE\n"
"3. DISPLAY\n");
printf("OPTION> ");
scanf("%d",&cmd);
switch(cmd){
case 1:
printf("Please Enter your Key Value >");
scanf("%d",&val);
insertafter(val, &head);
main();
case 2:
main();
case 3:
displaylist();
main();
}
}

最佳答案

您的插入函数不起作用,因为您将位置发送到指针。而该函数只需要指针。

所以改变:

insertafter(val, &head);

为此:

insertafter(val, head);

它会起作用。

第二个问题是你每次都一次又一次地调用主函数,这导致调用 listinit() 函数并初始化每个指针。所以删除:

 main();

在这种情况下。尝试使用这样的东西:

do{
switch(cmd){
case 1:
printf("Please Enter your Key Value >");
scanf("%d",&val);
insertafter(val, &head);
break;

case 2:
break;
case 3:
displaylist();
break;
}while(cmd != 0);

现在应该可以了。并避免递归调用 main() 函数,因为这是一种非常糟糕的编程习惯,会导致类似这样的问题。并且在使用 switch...case 时使用 break 语句。

谢谢:)

关于C 链表插入和显示功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32120511/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com