如何使用以下结构创建新节点?

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

我正在尝试做一个开放的双重清单。如何使用给定的结构初始化/创建一个新节点?请注意,我不能更改函数参数,也不能更改结构。

给我们的结构是(我们无法更改其中的任何结构)

typedef struct Node
{
    void *data;
    struct Node *next;
    struct Node *prev;
} Node;

/* a linked list */
typedef struct LinkedList
{
    Node *head;
    Node *tail;
} LinkedList

我编写的用于初始化新节点的代码:

/* create a new node */
/* returns a pointer to the newly created node */
/* print an error message and return NULL if an error occurs */
Node *initialise_node(void)
{   
    Node *newnode;
    newnode = (Node *)malloc(sizeof(Node));
        if (newnode == 0)
        {
            fprintf(stderr, "Warning: Memory could not be allocated for the new node.");
            printf("\n");
            return 0;
        }
        else
        {
            newnode -> prev = 0;
            newnode -> next = 0;
        }
    return newnode;
}
c doubly-linked-list
1个回答
0
投票

您可以在函数中从用户获取值并初始化节点的数据,并且应将下一个和上一个指针设置为空。

Node *initialise_node(void)
{   
    Node *newnode;
    newnode = (Node *)malloc(sizeof(Node));
        if (newnode == 0)
        {
            fprintf(stderr, "Warning: Memory could not be allocated for the new node.");
            printf("\n");
            return 0;
        }
        else
        {
            int val;
            printf("enter data for node");
            scanf("%d",&val);
            newnode->data = val;
            newnode -> prev = null;
            newnode -> next = null;
        }
    return newnode;
}
© www.soinside.com 2019 - 2024. All rights reserved.