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

时间:2019-10-22 05:29:46

标签: c for-loop linked-list malloc structure

我正在尝试使用一个分配值的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;
  }

尽管在此程序中,头部按照我的意图指向0,但是有一种方法可以使for循环从0开始一直到n,并仍然产生相同的输出。我希望它看起来像(int for count = 0; count

1 个答案:

答案 0 :(得分:0)

首先,在您的代码中,您不需要多余的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看起来有点令人生畏,但是一旦掌握了它,它便是一个有用的工具。如果您还不满意(请使用),请使用第一种。

仅创建列表转发就值得付出努力吗?插入到列表的前面很容易,并且经过整理后,您的原始变体对我来说看起来干净紧凑。

相关问题