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

时间:2020-03-28 13:30:37

标签: c pointers struct linked-list singly-linked-list

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

我选择了链表的结构,因为我需要大量的添加和删除操作,而数组允许这样做,但是效率较低。不过,我希望能够修改列表中的某些元素。为此,我曾想像过这样的功能:

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.
}

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

1 个答案:

答案 0 :(得分:1)

似乎该函数应该定义为类似

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; 
}
相关问题