简体   繁体   English

链接列表和结构

[英]Linked Lists and structs

I'm working on a school project and I'm trying to understand doubly linked lists and structs a bit better. 我正在开展一个学校项目,我正在尝试更好地理解双重链接列表和结构。 Currently, I'm trying to implement a function, one that creates a new linked list. 目前,我正在尝试实现一个创建新链接列表的功能。 Because I think I can work from there. 因为我认为我可以从那里工作。

typedef struct ListItem {
    struct ListItem *previousItem; //pointer to previous item, NULL if first list item
    struct ListItem *nextItem;     //pointer to next item, NULL if first list item
    void *data;                    //pointer to data

This is the struct for the doubly linked list I am trying to make. 这是我试图制作的双向链表的结构。 I know that a "void *" can hold a pointer to anything, also that I have to allocate any data stored in the list item. 我知道“void *”可以包含指向任何内容的指针,我也必须分配存储在列表项中的任何数据。

/**
 * This function starts a new linked list. Given an allocated pointer to data it will    return a
 * pointer for a malloc()ed ListItem struct. If malloc() fails for any reason, then this function
 * returns NULL otherwise it should return a pointer to this new list item. data can be NULL.
 *
 * @param data The data to be stored in the first ListItem in this new list. Can be any valid 
 *             pointer value.
  * @return A pointer to the malloc()'d ListItem. May be NULL if an error occured.
 */

ListItem *NewList(void *data);

I know that malloc() allocates enough memory on the stack for use, so I think that in my function I have to malloc() *previousItem, *nextItem, and *data (which would be 6 bytes?) Other than that, to implement the function all I would do is copy the ListItem struct? 我知道malloc()在堆栈上分配足够的内存供我们使用,所以我认为在我的函数中我必须使用malloc()* previousItem,* nextItem和* data(这将是6个字节?)除此之外,到实现函数我要做的就是复制ListItem结构? The previous AND next item would be NULL pointers since it is the only item in the list, and the *data would be the input I think. 前一个AND下一个项目将是NULL指针,因为它是列表中唯一的项目,*数据将是我认为的输入。 Can anyone give me an idea of what my code would look like? 谁能让我知道我的代码会是什么样子?

You're on the right track. 你走在正确的轨道上。 Instead of using 6 as the argument to malloc , you could use sizeof to get the amount of memory that you need to allocate - for example: 您可以使用sizeof来获取需要分配的内存量,而不是使用6作为malloc的参数 - 例如:

ListItem *node = malloc(sizeof(ListItem));

After that the implementation is fairly trivial: 之后,实施相当简单:

/* Make sure that allocation succeeded */
...
/* Assign the right values to previousItem and nextItem */
...
/* Assign the right value to data */
...
/* Return the pointer to the new list */
...

Someone else will probably submit the full function, but your english language description of what needs to happen is spot on (other than the whole heap vs. stack thing). 其他人可能会提交完整的功能,但您需要发生的英语语言描述(除了整个堆与堆栈之外的东西)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM