c++ - 当我在 C++ 中使用 Node(key,data) 而不是 Node.key 和 Node.data 时,单链表不起作用
问题描述
创建了一个节点以在单链表中使用,节点通过这两种方法创建成功,即 n.key、n.data 和 n(data,key)
当我使用 n.key, n.data 方法时代码可以正常工作但是当我使用 n(key, data) n1 被附加但 n2 未能执行
#include <iostream>
using namespace std;
class Node{
public:
int key,data;
Node* next;
Node(){
key = 0;
data = 0;
next = NULL;}
Node(int k, int d){
key = k;
data = d;
cout<<"Node created"<<endl;}};
class Singly_Linked_List{
public:
Node* head;
Singly_Linked_List(){head = NULL;}
Singly_Linked_List(Node* n){head = n;}
Node* KeyExists(int k){
Node* ptr = head;
while(ptr!= NULL){
if((ptr -> key) == k){return ptr;}
ptr = ptr -> next;}
return NULL;}
void Append_Node(Node* n){
if (head == NULL){head = n;
cout<<"Node appended"<<endl;}
else if(KeyExists(n->key)!=NULL){cout<<"Key already exists"<<endl;}
else{Node* ptr = head;
while(ptr -> next != NULL){ptr = ptr -> next;}
ptr -> next = n;
cout<<"Node appended"<<endl;}}};
int main(){
/*
Node n1,n2;
n1.key = 1;
n1.data = 10;
n2.key = 2;
n2.data = 20;
*/
Node n1(1,10),n2(2,10);
Singly_Linked_List s;
s.Append_Node(&n1);
s.Append_Node(&n2);
return 0;
}
解决方案
接受两个参数的构造函数不会初始化next
:
Node(int k, int d){
key = k;
data = d;
next = NULL; // <--- was missing
}
推荐阅读
- c# - 范围服务中的 IMemoryCache
- python - odeint Python 的问题
- java - Kotlin Gradle 插件:如何访问 `Project` 扩展,例如`sourceSets`?
- c# - 如何使用 System.Net.WebSockets 发送和接收碎片数据
- toit - 如何将气象站数据存储到 Toit 指标中?
- linux - VScode 源代码控制在 Ubuntu 上失败
- python - 使用值准则迭代排列的最快方法
- javascript - 尝试声明主体类时可以使用“=”吗?
- artifactory - 如何使用 Artifactory 查询语言进行逆查询?
- javascript - 为什么我的 JS 的“点击事件”只运行一次?