链表在c++开头打印0值

Linked List Printing 0 value at beginning c++

本文关键字:打印 开头 c++ 链表      更新时间:2023-10-16

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

这是代码List.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);
};

我的列表.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;
}

您从未初始化头部节点,因此您在下面的代码中写入未分配的内存。

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时都显式设置它。