相关疑难解决方法(0)

一个有趣的C链表成语

我正在接受一个C位置的采访,他们向我展示了一个我以前没有遇到的习语.这是一个简化涉及链表的各种算法的实现的技巧,我想知道是否有其他人遇到过这个问题.

假设我们定义了一个链表记录:

typedef struct _record
{
    char* value;
    struct _record* next;
} record;
Run Code Online (Sandbox Code Playgroud)

我们需要一个插入新记录的函数,以便整个列表保持对记录中的值进行排序.以下实现比我将使用的任何内容都简单,尽管可读性较差.

void insert_sorted(record** r, const char* value)
{
    record* newrec = NULL;
    while(*r && strcmp(value, (*r)->value) > 0)
        r = &((*r)->next); /* move r to point to the next field of the record */
    newrec = malloc(sizeof(record));
    newrec->value = strdup(value);
    newrec->next = *r;
    *r = newrec;
}
Run Code Online (Sandbox Code Playgroud)

调用该函数时,r指向列表的头指针.在while循环期间,r被更新为指向next我们想要放入新记录的点之前的记录字段.函数的最后一行要么更新列表的头指针(如果插入的话)发生在开头)或next前一个记录的字段,这很酷.

几个问题:

  • 这个成语是否有名称或在任何文献中都提到过?

  • 在C语言中还有其他类似的吗?

我以为我非常了解C并且很好地指出了指针和间接,但是这个让我花了一些时间来完全理解.

c idioms

11
推荐指数
2
解决办法
2760
查看次数

理解使用本地引用构建链表的逻辑

下面是使用本地参考逻辑创建链表的代码.无法理解for循环中的代码,尤其是第二行.(见// HERE)

有人可以详细说明这种逻辑是如何运作的.

void push(struct Node** head_ref, int new_data)
{
  struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
  newNode->data = new_data;

  newNode->next = *head_ref;
  *head_ref = newNode;

  return;
}


struct Node* buildWithLocalRef()
{
  int i=0;
  struct Node *head = NULL;
  struct Node **lastptrRef = &head;

  for(i=1;i<6;i++)
  {
    push(lastptrRef,i);
    lastptrRef = &((*lastptrRef)->next); // HERE
  }

  return head;
}

int main()
{
  struct Node* head;

  head = buildWithLocalRef();
  printList(head);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

c linked-list

1
推荐指数
1
解决办法
75
查看次数

标签 统计

c ×2

idioms ×1

linked-list ×1