c - 结构链表中的元素编号

标签 c list struct linked-list element

我正在尝试编写一个函数,该函数将结构链表作为参数。这些结构的元素之一是用于存储位置的值,例如结构#3 的元素为 3。进来的名单没有按顺序排列。我想遍历链表中的每个元素并根据它们的顺序设置值。我该怎么做?

nodeT numberStructs(nodeT *temp)
{
    int i;
    i=0;
    while(temp!=NULL)
    {
    temp->struct.struct_order=i;
    temp=temp->next;
    i++;
    }
    return temp;
}

这显然不会削减它,但这是我到目前为止所得到的。 另外,为了澄清,我将添加元素、移动元素、删除元素等。我不想每次都调整计数来改变行顺序,我想调用一个函数来理顺这些。这使我可以在需要更改时更改链表结构的指针。

最佳答案

typedef struct NodeT {
  struct Node *next;
  int struct_order;
  ...
} NodeT;

void fill_idx(NodeT *first) {
  int idx;
  NodeT *node;
  for (node = first, idx = 0;
       node;
       node = node->next, ++idx) {
    node->struct_order = idx;
  }
}

等价于 while 循环:

void fill_idx(NodeT *first) {
  int idx = 0;
  NodeT *node = first;
  while (node) {
    node->struct_order = idx;
    node = node->next;
    ++idx;
  }
}

关于c - 结构链表中的元素编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23303944/

相关文章:

python - 将 Cython 中的 numpy 数组传递给需要动态分配数组的 C 函数

c - 从 C 文件中扫描数字

c - 接受 int64_t 的输入

java - 这是否返回一个空列表?

c - C中的外部函数修改结构体数组

html - 正确使用gumbo-parser来迭代并找到我需要的东西?

python - 如何将字典列表转换为....?

android - 我正在创建一个类似Uber的应用程序,但它突然崩溃,并出现预期的BEGIN_ARRAY错误,但在第1行第1列路径$ STRING

C 结构问题

swift - 如何从数组中的结构检索结果