簡體   English   中英

C ++鏈接列表和指針到指針

[英]C++ Linked Lists and Pointers to Pointers

第一篇文章,但我已經潛伏了一段時間:)

首先,我正在嘗試在Visual Studio 2015中執行此框架代碼,根據我的老師的說法,它應該可以正常工作,因此我不確定還有哪些其他錯誤的客戶端可能會導致這種情況。

最后,這里的總體問題是我不確定如何完成剩余命令。 我了解指針的工作原理以及鏈接列表的基本概念,但並不完全。 我的第一個問題也沒有幫助。

任何幫助將不勝感激。

謝謝,

一些

#include <stdio.h>
#include <stdlib.h>


typedef struct _node {
    int value;
    struct _node *next;
} node;

void append(node**, int);
void prepend(node**, int);
void lprint(node*);
void destroy(node*);

int main(int argc, char **argv)
{
    node *head = NULL;

    append(&head, 1);
    append(&head, 2);
    append(&head, 3);

    prepend(&head, 0);
    prepend(&head, -1);
    prepend(&head, -2);

    lprint(head);
    destroy(head);

    return 0;
}

void append(node **head, int value)
{
    if (*head == NULL)
    {
        *head = (node*)calloc(0, sizeof(node));
        (**head).value = value;
    }
    else
    {
        node *temp;
        for (temp = *head; (*temp).next != NULL; temp = temp->next);
        (*temp).next = (node*)calloc(0, sizeof(node));
        (*temp).(*next).value = value;
    }
}

void prepend(node **head, int value)
{

}

void lprint(node *head)
{
    node *temp;
    for (temp = head; temp != NULL; temp = temp->next)
    {
        printf("%d ", temp->value);
    }
    printf("\n");
}

void destroy(node *head)
{

}

更改此行后,我能夠編譯並運行您的代碼:

    (*temp).(*next).value = value;

對此:

    (*temp).next->value = value;

當我運行它時,它打印出來:

1 2 3

鑒於未實現prepend(),這是我期望的。

我可以編寫prepend()的實現並將其發布到此處,但是我不想冒着為您做功課的風險; 相反,我只會描述prepend()應該如何工作。

對於head為NULL的情況, prepend()可以做與append()完全相同的事情:分配一個節點並將head設置為指向該節點。

在另一種情況下, head為非NULL(因為列表為非空),也很容易-甚至比append()實現容易。 您需要做的就是分配新節點,將新節點的next指針設置為指向現有的head節點(* head),然后將head指針(* head)設置為指向新節點。

destroy()函數可以用非常類似於一個在你的循環工作lprint()你必須抓住-功能,有一點需要注意next之前指針出給定節點的(並存儲到一個局部變量) free()節點,因為如果先釋放該節點,然后嘗試從已釋放的節點讀取下一個指針,則您正在讀取已釋放的內存,這是一個no-no(未定義的行為),並且會導致錯誤事情(tm)發生。

暫無
暫無

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

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