gpt4 book ai didi

在C中创建和显示线性链表(递归)

转载 作者:行者123 更新时间:2023-11-30 19:33:57 29 4
gpt4 key购买 nike

我正在尝试用c语言递归地创建线性链表,但继续坚持下去,代码无法正常工作,并出现错误“链接器工具错误 LNK2019”。可悲的是我不明白发生了什么事。这是我的代码。

感谢您提前提供的大力帮助。

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


struct node
{
char num; //Data of the node
struct node *nextptr; //Address of the next node
};
typedef struct node element;
typedef element *link;
link head;


void displayList(); // function to display the list

int main()
{
char s[] = "abc";
link stol(s);
{
link head;
if (s[0] == '\0')return(NULL);
else {
head = (link)malloc(sizeof(element));
head->num = s[0];
head->nextptr = stol(s + 1);
return(head);
}
}

printf("\n\n Linked List : To create and display Singly Linked List :\n");
printf("-------------------------------------------------------------\n");

displayList();
return 0;
}


void displayList()
{
link tmp;
if (head == NULL)
{
printf(" List is empty.");
}
else
{
tmp = head;
while (tmp != NULL)
{
printf(" Data = %d\n", tmp->num); // prints the data of current node
tmp = tmp->nextptr; // advances the position of current node
}
}
}

最佳答案

您在 main() 函数中重新定义了一个名为 headlink 对象。它隐藏了全局 head 变量。

删除 main 中的定义可以解决您的问题,但您应该考虑将 link* 作为参数传递给您的 displayList 函数任何情况。

我刚刚注意到 main() 中的这个语句 return(head);。您的程序也会因此过早退出。

每次我查看您的应用程序时,我都会发现更多问题。如果我是你,我会首先创建一个向列表添加节点的函数。将新节点添加到列表的前面要容易得多,因此您应该首先尝试这样做。运行后尝试添加到尾部。添加到尾部非常相似,但是您必须“首先遍历列表才能到达最后一个元素,就像您在 displayList() 中所做的那样”另一种方法是保留最后一个元素的地址您已添加到列表中的节点*。就像我说的,它增加了一点复杂性,所以首先让它与 addToHead 一起工作。

void addToHead(link* l, node* n)
{
n->nextptr = l->nextptr;
l->nextptr = n;
}

在 main 中,您可以一次分配一个新节点,就像使用 malloc() 所做的那样。使用整数初始化其内容num,并让addToHead 处理指针内容。您对指针的使用很糟糕,但列表非常简单,并且 addToList 几乎显示了指针中可以放入什么以及应该放入什么 - 即其他指针。

您可以在第一个 printf 之前删除 main() 中的几乎所有内容。你必须

  1. 开始循环:
  2. 编写提示,以便用户知道如何使用 printf()
  3. 使用 scanf("%d", &n) 或等效函数读取用户的输入。
  4. 如果用户输入负值,则退出循环。
  5. malloc() 一个新节点
  6. 设置其数据num = n
  7. 调用addToHead添加节点。
  8. 循环直到用户输入空字符串或-1。

这应该需要大约 8 到 10 行代码。如果有疑问,您可以通过 google 或 http://en.cppreference.com/w/c 轻松找到 scanf 上的文档。 .

关于在C中创建和显示线性链表(递归),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44605695/

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