链表在c++开头打印0值
Linked List Printing 0 value at beginning c++
我正在通过创建一个简单的链表类来刷新我的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
时都显式设置它。
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 在gem5中打印文件中的所有cache_blocks
- 如何打印以特定字符开头的单词数?
- 打印以 "a" 开头的单词(字符串中)
- 链表在c++开头打印0值