Can you help me debug this c program which is supposed to add a node at the end in circular single linked list and print the list?
using namespace std;
class Node
{
public:
int data;
Node* next;
Node(int x)
{
data = x;
next = NULL;
}
};
class Lfun
{
public:
virtual void addLast(int x) = 0;
virtual void display() = 0;
virtual ~Lfun(){};
};
class List :public Lfun{
private:
Node* head;
Node* curr;
public:
List()
{
head = NULL;
curr = NULL;
}
void addLast(int x)
{
Node *tmp = new Node(x);
tmp->next = head;
if (head == NULL)
{
head = tmp;
}
else
{
curr = head;
while (curr->next != NULL)
{
curr = curr->next;
}
curr->next = tmp;
}
}
void display()
{
curr = head;
for (int i = 0; i < 5; i )
{
cout << curr->data << " ";
}
}
};
int main()
{
List* ll = new List();
for (int i = 0; i < 5; i )
{
cout << i;
ll->addLast(i);
ll->display();
}
}
I have created a class 'Node' to create a node for the linked list and another class 'Lfun' to redefine all the functions in the child class ,that is 'List'. The program is not giving any output, can you explain why that is happening and how I can fix that problem?
CodePudding user response:
Your main problem is this line in List:
tmp->next = head;
With that line, you ensure that the last Node's next
will never be NULL, but point back at head, giving you a circular list.
In your while-loop you loop until you find a next member that is NULL, but due to the above problem, this will loop forever.
Your display
function is also broken, as it prints the first element 5 times without advancing curr
. Another thing is that curr
should really not be a member variable, but rather a local variable in functions where it is used.
Also note that in c , you should use nullptr
, not NULL