gpt4 book ai didi

C中根据用户请求的元素个数创建链表

转载 作者:太空宇宙 更新时间:2023-11-03 23:39:49 25 4
gpt4 key购买 nike

所以我想创建一个双向链表的节点结构:

typedef struct Node { //node structure
int value;
struct Node *next;
struct Node *previous;
} node;

起初,我创建了如下列表:

//allocate memory for the nodes
node *first = malloc(sizeof(*first));
node *second = malloc(sizeof(*second));
node *third = malloc(sizeof(*third));
node *fourth = malloc(sizeof(*fourth));
node *fifth = malloc(sizeof(*fifth));

{ //define the nodes and link them together.(circular linked list)
first->value = 1;
first->next = second;
first->previous = fifth;

second->value = 2;
second->next = third;
second->previous = first;

third->value = 3;
third->next = fourth;
third->previous = second;

fourth->value = 4;
fourth->next = fifth;
fourth->previous = third;

fifth->value = 5;
fifth->next = first;
fifth->previous = fourth;
}

但后来我意识到我不知道列表是否应该由 5 个元素组成,想向用户询问列表的大小。问题是,当我尝试实现一个名为 createList() 的函数并将列表大小作为参数传递时,我不知道应该如何创建这样的列表。我想首先使用 ->next->previous 值创建一个临时指针作为 NULL 但是我将如何遍历输入 n 并在 next 节点为 NULL 时创建新节点?

谢谢

最佳答案

你必须创建新节点 n(input size) 次并附加到链表的尾部,你可以使用任何循环构造来创建新节点,下面是示例代码。已编辑:循环双向链表的条件,早些时候我注意到您要求循环 dll,我认为它只是 dll。

#include<stdio.h>
#include<stdlib.h>
typedef struct Node { //node structure
int value;
struct Node *next;
struct Node *previous;
} node;

void createList(struct Node ** head, int size) {

// temp variable to iterate list
struct Node *temp = *head;
int val;
while (size--) {
scanf("%d", &val);


if (temp == NULL) {
// create head node for empty linked list;
struct Node *node = (struct Node*)malloc(sizeof( Node));
node->previous = NULL;
node->next = NULL;
node->value = val;
*head = node;
temp = node;
} else {
// if head node exists append the numbers at the end of the linkedlist
struct Node *node = (struct Node*)malloc(sizeof(struct Node));
node->previous = temp;
node->next = NULL;
node->value = val;
temp->next = node;
temp = temp->next;
}
}

// for circular linked list
temp->next = *head;
(*head)->previous = temp;
}

void printList (struct Node *head) {
node *temp = head;
while (head->next != temp) {
printf("%d\n", head->value);
head = head->next;
}
// print last node
printf("%d\n", head->value);
}
int main () {

struct Node *head = NULL;
int size;
scanf("%d", &size);
createList(&head, size);
printList(head);
return 0;
}

关于C中根据用户请求的元素个数创建链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48861301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com