您的代码有两个小问题:
- 在创建节点时,使用了一个名为
perple
的字符数组来接收输入,但实际上应该是type
字段。您需要将scanf("%s", perple);
改为scanf("%s", node->type);
。 - 在循环插入节点时,不需要将
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助手提供,问题来源于学员提问