'Using Constructor v/s static method for basic linked list
I've tried implementing a basic linked list in my first try I implemented a static method (insert) for inserting data and pointer to the next element like shown below:
#include <iostream>
using namespace std;
class Node{
public:
int data = NULL;
Node* next = nullptr;
Node(){}
static void insert(int data, Node* next,Node* obj){
obj->data = data;
obj->next = next;
}
static void printList(Node* n){
while(n != nullptr){
cout << n->data << " ";
n = n->next;
}
}
};
int main()
{
Node* head = nullptr;
Node* second = nullptr;
Node* third = nullptr;
head = new Node();
second = new Node();
third = new Node();
//via static method
Node::insert(1,second,head);
Node::insert(2,third,second);
Node::insert(3,nullptr,third);
Node::printList(head);
delete head;
delete second;
delete third;
return 0;
}
it's working fine as I expect (getting output as 1 2 3), but when I implement it using constructors like show below:
#include <iostream>
using namespace std;
class Node{
public:
int data = NULL;
Node* next = nullptr;
Node(){}
Node(int data, Node* next){
this->data = data;
this->next = next;
}
static void printList(Node* n){
while(n != nullptr){
cout << n->data << " ";
n = n->next;
}
}
};
int main()
{
Node* head = nullptr;
Node* second = nullptr;
Node* third = nullptr;
//via constructors.
head = new Node(1,second);
second = new Node(2,third);
third = new Node(3,nullptr);
Node::printList(head);
delete head;
delete second;
delete third;
return 0;
}
I am getting the output as 1 0. When I call constructor from third to head it's working fine (by that I mean)
third = new Node(3,nullptr);
second = new Node(2,third);
head = new Node(1,second);
Kindly explain why is it behaving like that. Note: I am a beginner in programming.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
