簡體   English   中英

鏈接列表和結構

[英]Linked Lists and structs

我正在開展一個學校項目,我正在嘗試更好地理解雙重鏈接列表和結構。 目前,我正在嘗試實現一個創建新鏈接列表的功能。 因為我認為我可以從那里工作。

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

這是我試圖制作的雙向鏈表的結構。 我知道“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);

我知道malloc()在堆棧上分配足夠的內存供我們使用,所以我認為在我的函數中我必須使用malloc()* previousItem,* nextItem和* data(這將是6個字節?)除此之外,到實現函數我要做的就是復制ListItem結構? 前一個AND下一個項目將是NULL指針,因為它是列表中唯一的項目,*數據將是我認為的輸入。 誰能讓我知道我的代碼會是什么樣子?

你走在正確的軌道上。 您可以使用sizeof來獲取需要分配的內存量,而不是使用6作為malloc的參數 - 例如:

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

之后,實施相當簡單:

/* 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 */
...

其他人可能會提交完整的功能,但您需要發生的英語語言描述(除了整個堆與堆棧之外的東西)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM