首页 > 解决方案 > 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)

标签: cpointers

解决方案


我建议这样做:

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);

推荐阅读