簡體   English   中英

當我打印單鏈接列表時,為什么會有一個虛擬節點?

[英]Why there is a dummy node when I am printing a singly linked list?

我的代碼為什么打印一個額外的節點(垃圾值)? 我的代碼有問題嗎? 讓我來解決這個問題。

void push(node **head_ref,int value)  //function to insert a new node on front of the list
{
    node *new_node=(node*)malloc(sizeof(node));
    new_node->data=value;
    new_node->next=*head_ref;
    *head_ref=new_node;
}

void printll(node *head)    //function to print the list
{
    node *temp = head;
    while(temp!=NULL)
    {
        printf("%d ",temp->data);
        temp=temp->next;
    }
}

實際輸出:
45 88 24 34 77 0

預期產量:
45 88 24 34 77


完整代碼:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cassert>

using namespace std;

struct node
{
    int data;
    node *next;
};

void push(node **head_ref,int value)
{
    node *new_node=(node*)malloc(sizeof(node));
    new_node->data=value;
    new_node->next=*head_ref;
    *head_ref=new_node;
}

void printll(node *head)
{
    node *temp = head;
    while(temp!=NULL)
    {
        printf("%d ",temp->data);
        temp=temp->next;
    }

}

int main()
{
    node *head= (node*)malloc(sizeof(node));
    push(&head,77);
    push(&head,34);
    push(&head,24);
    push(&head,88);
    push(&head,45);
    printll(head);
    printf("\n");
    return 0;
}

當您使用malloc分配內存時,不會以任何方式初始化內存,它的內容是不確定的 這意味着,當您分配第一個節點(不需要的虛擬額外節點)時,它的next指針不為null,並且取消引用該不確定的指針會導致未定義的行為

最簡單的解決方案? 考慮到您的代碼比C比C ++更接近C,因此根本不分配內存,而只是創建一個指針並將其初始化為NULL

node *head = NULL;

在C ++中執行此操作的一種正確方法是根本不使用malloc ,而使用C ++運算符new並向初始化它的node結構添加構造函數:

struct node
{
    node() : data(0), next(nullptr) {}
    node(int d, node* n) : data(d), next(n) {}

    int data;
    node* next;
};

void push(node** head_ref, int value)
{
    *head_ref = new node(value, *head_ref);
}

...

int main()
{
    node* head = nullptr;
    ...
}

現在,您可以創建一個新節點,它的初始value 0next指針為空指針。 如上所示,您還可以創建和初始化具有特定valuenext的新節點。

[如果您的編譯器不支持C ++ 11 nullptr值,則將nullptr替換為0 ]

代替這個定義

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

你應該簡單地寫

node *head = NULL;

要么

node *head = nullptr; // C++

否則,您的程序將具有未定義的行為,因為未初始化頭分配的節點。

另外,如果它是C ++程序,則應使用運算符new而不是C函數malloc 例如功能push看起來像

void push( node * &head_ref, int value )
{
    head_ref = new node { value, head_ref };
}

叫像

push( head, 77 );

考慮到您還必須編寫一個函數,該函數將為列表釋放所有分配的內存。

您的設計中有一個虛擬節點(頭部本身)。 因此,打印功能需要跳過該虛擬節點。

暫無
暫無

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

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