【问题标题】:C Linkedlist Insertation Not Working and Display FunctionC链表插入不起作用和显示功能
【发布时间】:2015-08-20 14:07:51
【问题描述】:

我正在尝试实现一个链表。但不幸的是它不起作用。我尝试更改代码。它不起作用。插入函数不起作用,当我调用 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();
    }
}

【问题讨论】:

    标签: c linked-list


    【解决方案1】:

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

    所以改变:

    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 语句。

    谢谢:)

    【讨论】:

    • 嗨哈立德,谢谢它对我有用。完全有效。 :) 我太笨了,没看到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多