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

问题描述 投票:0回答:1

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

c for-loop linked-list malloc structure
1个回答
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看起来有些令人生畏,但是一旦掌握了它,它便是有用的工具。如果您对此还不满意,请使用第一个变体。

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

© www.soinside.com 2019 - 2024. All rights reserved.