当我在 C++ 中使用 Node(key,data) 而不是 Node.key 和 Node.data 时,单链表不起作用
Singly Linked List Doesn't work when i am using Node(key,data) rather than Node.key and Node.data in C++
创建了一个在单链表中使用的节点,两种方法都成功创建了节点
即 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
}
创建了一个在单链表中使用的节点,两种方法都成功创建了节点 即 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
}