使用for循环在C中创建链接列表以分配值

Creating Linked List in C using for loop for assigning values

我正在尝试使用分配值的 for 循环为我的程序创建链表。在创建此链表时,我希望能够跟踪头部并将 for 循环中的第一个值分配给头部。例如,如果我正在创建一个从 0 到 n - 1 的列表,我希望头部指向 0,列表的其余部分后跟 1-2-3-4-...-n-1。我已经编写了一个循环来执行此操作,但是,for 循环必须向后倒计时而不是向前倒计时。这是我的代码:

// Structure
typedef struct node {
  int value;
  struct node * next;
} ListNode;

  int size = "some value"; 

  ListNode * head = NULL; // beginning of the linked list
  ListNode * temp; // temporary node  

  for(int count = size - 1; count >= 0; count--)
  {
    // creates temporary nodes //
    ListNode * tempNode = malloc(sizeof(ListNode));
    tempNode -> value = count;
    tempNode -> next = NULL;
    // creation of node completed

    temp = tempNode;
    temp -> next = head;
    head = temp;
  }

虽然在这个程序中,head 如我所愿指向 0,但有没有办法让 for 循环从 0 开始一直到 n,并且仍然产生相同的输出。我希望它看起来像 (int for count = 0; count < n; count++)。我想知道这只是一种偏好。有知道的请帮忙,谢谢!

首先,在您的代码中,您不需要额外的 tempNode,只需使用 temp 并将其置于内部块的本地:

for (int count = size; count--; ) {
    ListNode *temp = malloc(sizeof(*temp));

    temp->value = count;
    temp->next = head;
    head = temp;
}

如果你想在最后追加元素,你应该保留一个指向最后一个节点的指针,tail:

ListNode *head = NULL;
ListNode *tail = NULL;

for (int count = 0; count < size; count++) {
    ListNode *temp = malloc(sizeof(*temp));

    temp->value = count;
    temp->next = NULL;

    if (tail == NULL) {
        head = temp;
        tail = temp;
    } else {
        tail->next = temp;
        tail = temp;
    }
}

有一种更优雅的方法可以做到这一点:不是保留指向最后一个节点的指针,而是保留指向下一个元素应该去的空指针的指针:

ListNode *head = NULL;
ListNode **tail = &head;

for (int count = 0; count < size; count++) {
    ListNode *temp = malloc(sizeof(*temp));

    temp->value = count;
    temp->next = NULL;

    *tail = temp;
    tail = &(*tail)->next;
}

一开始,*tail保存的是head的地址,之后会保存最后一个节点的next成员的地址。您可以通过指针 tail 更新两者,而无需检查列表是否为空。

最后一种方法的 ListNode **tail 一开始看起来有点令人生畏,但是一旦掌握了它,它就是一个有用的工具。如果您(还)对它不满意,请使用第一个变体。

仅创建转发列表值得吗?插入前面的列表很容易,整理后,您的原始变体对我来说看起来干净紧凑。