【问题标题】:How to get the pointer of an item from a linked list如何从链表中获取项目的指针
【发布时间】:2020-03-28 13:30:37
【问题描述】:

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

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

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 的地址,如果没有找到,则返回NULL。例如return &node->item; 这比“搜索列表的副本”更简单。

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


【解决方案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; 
}

【讨论】:

  • 这和我想的差不多,但关键是要保持链表完整,这就是让问题变得更复杂的原因。也许我的问题不够具体,我会编辑它。
  • @Foxy 你说链表必须完整是什么意思?该函数不会改变链表。
  • 对不起,确实有效。我以为循环的主体正在改变列表,但事实并非如此。谢谢你的回答!
猜你喜欢
  • 2012-10-06
  • 1970-01-01
  • 1970-01-01
  • 2014-11-29
  • 2021-01-07
  • 1970-01-01
  • 2018-06-14
  • 1970-01-01
  • 2020-06-14
相关资源
最近更新 更多