Reputation:
I am writing a code for singly linked list and I am facing problem in writing its insert function. It is not inserting the new nodes and not printing them. I am not able to find the problem. Any help will be appreciated.
Code:
#include <iostream>
using namespace std;
class Node{
int data;
Node * next;
public:
Node(int data_)
{
data = data_;
next = nullptr;
}
void insert(int no)
{
Node * index = this->next;
while (index != nullptr)
{
index = index->next;
}
index = new Node(no);
}
void print()
{
Node * index = this;
while (index != nullptr)
{
cout << index->data << ", ";
index = index->next;
}
}
};
int main()
{
Node * head = new Node(1);
head->insert(2);
head->insert(3);
head->insert(4);
head->insert(5);
head->print();
system("pause");
return 0;
}
Thanks
Upvotes: 0
Views: 102
Reputation: 206717
It looks to me like you were trying to insert the new item at the tail of the list. You had a small error in your insert
.
Here's a version that should work:
void insert(int no)
{
Node* index = this;
while (index->next != nullptr)
{
index = index->next;
}
index->next = new Node(no);
}
Explanation of error in your code
void insert(int no)
{
Node * index = this->next;
// When there is only one item in the linked list, which is true when
// you are trying to insert the second item, index gets set to NULL.
// The while loop does not get executed.
while (index != nullptr)
{
index = index->next;
}
// index points to the newly created node but 'this' has no link
// with index. As a consequence, 'this' never gets the second item appended
// at the end.
index = new Node(no);
}
Upvotes: 0
Reputation: 7100
Here's one way to fix your code:
class Node{
int data;
Node * next;
public:
Node(int data_, Node *ptr=nullptr) : data(data_), next(ptr) {}
void insert(int no) { next = new Node(no, next); }
void print() {
cout << data;
if (next != nullptr)
next->print();
}
};
Note the change in the constructor which makes things a little nicer and also note that there is no destructor at the moment so this will certainly leak memory until a proper destructor is defined.
The output of the program is now:
15432
Upvotes: 1