gpt4 book ai didi

在C中以相反的顺序将链表的元素复制到另一个链表

转载 作者:行者123 更新时间:2023-12-01 23:05:51 26 4
gpt4 key购买 nike

我是 C 语言编程的新手,正在学习一门类(class)。我在练习其中一项任务时遇到问题。我应该编写一个程序来创建 10 个字符的链表,然后以相反的顺序创建该列表的副本。我已经写了(主要是复制)了一段代码,但它只是反转了我的链表的内容,并没有将它们以相反的顺序复制到一个新的链表中。即使我使用的是 char 数据类型,它也不适用于字母。可以很好地处理数字。

这是我的代码:

#include <stdio.h>
#include <malloc.h>

struct Node
{
char data;
struct Node *next;
};

static void reverse(struct Node **head_ref)
{
struct Node *previous = NULL;
struct Node *current = *head_ref;
struct Node *next;
while (current != NULL)
{
next = current->next;
current->next = previous;
previous = current;
current = next;
}
*head_ref = previous;
}

void push(struct Node **head_ref, char new_data)
{
struct Node *new_node =
(struct Node *)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}

void printList(struct Node *head)
{
struct Node *temp = head;
while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}

int main()
{
struct Node *head = NULL;
char element = NULL;
printf("Enter 10 characters:\n");
for (int i = 0; i <= 9; i++)
{
scanf_s("%d", &element);
push(&head, element);
}

printf("Given linked list\n");
printList(head);
reverse(&head);
printf("\nReversed Linked list \n");
printList(head);
getchar();
}

最佳答案

这个for循环

for (int i = 0; i <= 9; i++)
{
scanf_s("%d", &element);
push(&head, element);
}

调用未定义的行为,因为对 char 类型的对象使用了不正确的转换说明符 %d

你需要写

for (int i = 0; i <= 9; i++)
{
scanf_s( " %c", &element, 1 );
push(&head, element);
}

注意格式字符串中转换说明符%c前的空格。这允许跳过输入流中的空白字符。

至于函数,则可以使用您已经定义的函数 push 通过以下简单方式声明和定义它

struct Node * reverse_copy( const struct Node *head )
{
struct Node *new_head = NULL;

for ( ; head != NULL; head = head->next )
{
push( &new_head, head->data );
}

return new_head;
}

在 main 中你可以这样写

struct Node *second_head = reverse_copy( head );

考虑到函数 push 如果处理节点内存分配失败的情况会更安全。

关于在C中以相反的顺序将链表的元素复制到另一个链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70899561/

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