【问题标题】:Linked List Printing 0 value at beginning c++链表在开头 c++ 打印 0 值
【发布时间】:2023-03-28 23:55:02
【问题描述】:

我正在通过创建一个简单的链表类来刷新我的 C++。我遇到的问题是当我尝试打印列表时,列表开头的打印为零。我怎样才能摆脱这个?另外,我的第二个构造函数有问题。我该怎么办?`

这里是代码 列表.h

#ifndef NODE_H
#define NODE_H


class List{
    private:
        typedef struct Node{
            int data;
            struct Node* next;
        }* node;

        node head;
        int listLength;

    public:
        List();
        List(int data, node nextLink);
        void printList();
        void push(int data);
        void Delete(int d);
        int listSize(void);
};

我的 List.cpp

#endif

#include "node.h"
#include <iostream>
using namespace std;

List::List(){
    head->data=0;
    head->next= NULL;
    listLength=0;
}

List::List(int data, node nextLink){
    head=NULL;
    listLength++;
}

void List::push(int data){



    if(head==NULL){
        head->data=data; 
        head->next= NULL;
    }
    else{
        node cursor = head;
        while(cursor->next != NULL)
            cursor = cursor -> next;

        node newNode= new Node;
        newNode->data=data;
        newNode->next=NULL;
        cursor->next= newNode;
    }
    listLength++;
}

void List::printList(){
    node cursor=head;
    while(cursor!=NULL){
        //if(cursor->data==0){cursor=cursor->next;}
        if(cursor->next==NULL){
            cout<<cursor->data<<endl;
            return;
        }
        else{
            cout<<cursor->data<<" -> ";
            cursor=cursor->next;
        }

    }
    cout<<endl;
}
int main(){ 
    List li;
    li.push(2);
    li.push(3);
    li.push(0);
    li.push(4);
    li.printList();
    return 0;
}

【问题讨论】:

    标签: c++ printing linked-list


    【解决方案1】:

    你从不初始化你的头节点,所以你在下面的代码中写入未分配的内存。

    if(head==NULL){
        head->data=data; 
        head->next= NULL;
    }
    

    应该是:

    if(head==NULL){
        head = new Node; // added this line
        head->data=data; 
        head->next= NULL;
    }
    

    你可能还想要第一个构造函数

    List::List(){
        head->data=0;
        head->next= NULL;
        listLength=0;
    }
    

    改为

    List::List(){
        head = NULL;
        listLength=0;
    }
    

    至于第二个构造函数,我假设你想要这样的东西?

    List::List(int data, node nextLink){
        head = new Node;
        head->data = data;
        head->next = nextLink;
        listLength = 1;
    }
    

    如果没有,你能更好地解释你想要什么吗?

    我还要注意,通常认为为Node 结构创建一个将next 初始化为NULL 的构造函数是一种良好的编程习惯,这样您就不必每次都显式设置它在整个代码中创建 new Node

    【讨论】:

    • 感谢您的回复。我已经尝试过你的建议,但在列表的乞求时我仍然得到零。
    • 仔细检查一下。你注意到编辑了吗? ideone.com/8HDsTA 运行成功,输出 2 -&gt; 3 -&gt; 0 -&gt; 4
    • 是的,我看到了编辑,我看到它在那个网站上运行。不知何故,我仍然得到零。构造函数虽然谢谢你。我不明白为什么它不起作用。
    • 不过,我看到你接受了我的回答。你还在烦恼吗?如果是这样,您应该使用 MCVE 编辑 OP。
    猜你喜欢
    • 2016-10-13
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 2021-02-18
    • 2016-06-15
    • 1970-01-01
    相关资源
    最近更新 更多