Created a Node to use in Singly Linked List, Nodes are getting successful created by both methods ie n.key, n.data and n(data,key)
Code Works Properly when I use n.key, n.data method But when I use n(key, data) n1 got appended but n2 failed to do
#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;
}
The constructor that takes the two arguments does not initialise next
:
Node(int k, int d){
key = k;
data = d;
next = NULL; // <--- was missing
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.