ZBLOG

#include #include typedef struct List { int id; char type[3]; struct List *next; //向后指针 struct List *prev; //向前指针 } Node; Node *create_node(int b,char type[3]) { int index = 0; Node *newNode = (Node*...

您的代码有两个小问题:

  1. 在创建节点时,使用了一个名为 perple 的字符数组来接收输入,但实际上应该是 type 字段。您需要将 scanf("%s", perple); 改为 scanf("%s", node->type);
  2. 在循环插入节点时,不需要将 node = node->next;。因为插入操作只是改变指针的指向,并不需要手动移动到下一个节点。

以下是修改后的代码:

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

typedef struct List
{
    int id;
    char type[3];
    struct List *next;   //向后指针
    struct List *prev;  //向前指针
} Node;

Node *create_node(int b, char type[3])
{
    int index = 0;
    Node *newNode = (Node*)malloc(sizeof(Node));
    newNode->id = b;
    for(index = 0; index < 3; index++)
    {
        newNode->type[index] = type[index];
    }
    newNode->prev = NULL;
    newNode->next = NULL;

    return newNode;
}

void insert_node(Node **head, Node *newNode) 
{
    if (*head == NULL) 
    {
        *head = newNode;
        return;
    }

     // 找到尾部节点
     Node *current = *head;

     while (current->next != NULL) 
     {
         current = current->next;
     }

     // 在尾部插入新节点
     current->next = newNode;
     newNode->prev = current;   
}

// 打印双链表元素
void printList(Node* node) 
{
    printf("双链表元素:\n");
    while (node != NULL) 
    {
        printf("%d %s\n", node->id, node->type);
        node = node->next;
    }
}

int main()
{
    Node *head = NULL;
    int index = 0;
    char type[3];
    
    for(index = 0; index < 10; index++)
    {
        scanf("%s", type);
        Node *node = create_node(index, type);
        insert_node(&head, node);
    }

    printList(head);

    return 0;
}

这样修改后的代码应该可以正常运行并输出双链表的元素。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=9379

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?