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

C Linkedlist Insertation Not Working and Display Function

我正在尝试实现链接 list.But 不幸的是它不是 working.I 已尝试更改代码。它没有 work.The 插入功能不起作用,而且当我调用 displaylist() 时我什么也没看到 function.Help 我出去 please.Here 是我的代码:

#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();
    }
}

您的插入功能不起作用,因为您将位置发送到 pointer.Where,因为该功能只需要指针。

所以改变:

insertafter(val, &head);

对此:

insertafter(val, head);

它会起作用。

第二个问题是您每次都一次又一次地调用 main 函数,这会导致调用 listinit() 函数,并且它会在每个 pointers.So 中初始化 Remove:

 main();

在 cases.And 中尝试使用这样的东西:

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() 函数,因为这是一种非常糟糕的编程习惯,会导致 this.And 在使用 switch...case 时使用 break 语句等问题。

谢谢:)