c - C中的链表从void函数返回一个指针
问题描述
我正在做家庭作业,但我不明白如何从 void 函数返回指针。这就是我下面的内容。有人可以帮助我或至少给我一个提示吗?谢谢!
typedef struct Node {
void *data;
struct Node *next;
} Node;
/* List: Represents a linked list. */
typedef struct List {
Node *head;
int size;
} List;
* Given: A pointer to a List structure
* Returns: The size of that list */
43 void *lstget(List *lst, int idx) {
42 Node *current = NULL;
43 int count;
44 bool found = false;
45
46 if(lst->head == NULL || idx > lst->size || idx < 0)
47 return NULL;
48 current = lst->head;
49
50 while(!found) {
51 if(count == idx) {
52 bool found = true;
53 /* THIS IS WHERE I WANNA DO IT */
54 }
55 current = current->next;
56 count++;
我正在考虑这样的事情,但我不确定它是否会起作用:
*lst = *((Node *)current->data)
解决方案
我建议这样做:
struct Node {
void* data;
Node* next;
}*head = NULL;
/*struct List {
Node* head;
int size;
}List1;*/
//I don't recommend this you can use a function to return list size
int length() {// return list size
int length = 0;
struct Node* current;
for (current = head; current != NULL; current = current->next) {
length++;
}
return length;
}
void* lstget(Node* lst, int idx) {
Node* current = NULL;//no need for this you can (Node* current = lst->head) from first
int count=0;
bool found = false;
int size = length();
if (lst == NULL || idx > size || idx < 0)
return NULL;
current = lst;
while (!found) {
if (count == idx) {
bool found = true;
Node* tmp = (Node*)malloc(sizeof(Node));
tmp = current;
return tmp;
}
current = current->next;
count++;
}
}
在您的主函数中,您可以像这样返回节点:
Node* tmp;//you can malloc too
//Node* tmp=(Node *)malloc(sizeof(Node)) but most likely no need
tmp = (Node*) lstget(head, 1);
推荐阅读
- javascript - 启用按钮功能
- json - Flutter 在状态更新时如何无法重新加载 FutureBuilder?
- java - 如何在 SSO React 应用程序中使用 SAML 和 JWT?
- asp.net-core - BlazorWASM:电子邮件在 DisplayLogin 上消失
- docusaurus - Docusaurus2:在 React 中导入本地化 MDX 的推荐方法?
- html - 将箭头指示器定位在正确位置的问题
- r - 如何从一个数据框制作一个具有相同值的更大数据框
- c# - c#一次从一个列表中取出两个元素
- next.js - 您如何在 Vercel 上的 Next JS 中提供静态站点(例如来自 Webflow 或登录页面生成器)?
- tensorflow - 如何排除预测以前看过的电影。TensorFlow 推荐器 (TFRS)