C 如何从链表中获取项目的指针

C 如何从链表中获取项目的指针,c,pointers,struct,linked-list,singly-linked-list,C,Pointers,Struct,Linked List,Singly Linked List,在链表中搜索并返回项目并不复杂:只需浏览列表的副本并返回与搜索谓词匹配的项目。然而,我想知道是否有一种方法可以检索我们在列表中查找的元素的指针,这意味着一个我无法克服的困难:不能有原始列表的副本(否则指针将无效或与原始列表中的项目不匹配) 我选择链表的结构是因为我需要大量的添加和删除,这是数组允许的,但效率较低。不过,我希望能够修改我的清单中的一些内容;为此,我设想了这样一个功能: struct Item { char* str; int value; }; typedef s

在链表中搜索并返回项目并不复杂:只需浏览列表的副本并返回与搜索谓词匹配的项目。然而,我想知道是否有一种方法可以检索我们在列表中查找的元素的指针,这意味着一个我无法克服的困难:不能有原始列表的副本(否则指针将无效或与原始列表中的项目不匹配)

我选择链表的结构是因为我需要大量的添加和删除,这是数组允许的,但效率较低。不过,我希望能够修改我的清单中的一些内容;为此,我设想了这样一个功能:

struct Item
{
    char* str;
    int value;
};

typedef struct Node
{
    struct Item item;
    struct Node *next;
} Node;

Node *push(Node *head, const struct Item)
{
    Node *new_node;
    new_node = malloc(sizeof(*new_node));
    new_node->item = item;
    new_node->next = head;
    head = new_node;
    return head;
}

Node *remove(Node *head, char* str)
{
    if (head == NULL)
        return NULL;

    if (!strcmp(head->item.str, str))
    {
        Node *tmp_next = head->next;
        free(head);
        return tmp_next;
    }

    head->next = remove(head->next, str);
    return head;
}

struct Item *get_item_ptr(const Node *head, char* str)
{
    // I would get the pointer of the structure Item that refers to the string `str`.
    ...
    return NULL; // I return `NULL` if no item meets this predicate.
}

我不知道如何在保持原始链表完整的同时做到这一点,我也不确定这是否是一个好主意,在这种情况下,我会简化为一个简单的数组(或另一个更合适的数据结构?)。

似乎该函数的定义如下

struct Item * get_item_ptr( const Node *head, const char *str )
{
    while ( head != NULL && strcmp( head->item.str, str ) != 0 )
    {
        head = head->next;
    }

    return head == NULL ? ( struct Item * )NULL : &head->item; 
}

返回找到匹配项的
struct项的地址
,如果未找到则返回
NULL
。例如
return&node->item这比“搜索列表副本”更简单。这是我所想到的,但关键是保持链接列表的完整性,这使问题变得更复杂。也许我的问题不够具体,我会编辑它。@Foxy你说链表必须完整是什么意思?此函数不会更改链表。对不起,它确实有效。我以为循环的主体正在改变列表,但事实并非如此。谢谢你的回答!