Please consider this C++ code for creation and traversing a linked list (number of nodes to be decided by user, not programmer)
#include <iostream>
using namespace std;
class Node
{
public:
int data; Node* next;
Node(int d, Node* j): data(d),next(j) {cout << "Constructor\n";}
};
int main()
{int n; Node* p; Node* q = 0;
while(cin >> n)
{ p = new Node(n,q);
q = p;}
for(;p->next; p=p->next)
cout << p->data << "->";
cout << p-> data << "->*\n";
return 0;}
The code above works perfectly, and can be terminated by the user using Ctrl+D followed by Enter. However if we replace while(cin >> n) with while (true) using cin >> n; inside the loop, as shown here
while(true)
{ cin >> n;
p = new Node(n,q); q = p;}
then upon the user attempting to terminate, the loop just goes on automatically creating new Nodes!! Why??
Thanks in advance
It keeps going because the loop condition is
true, making it an infinite loop. If you want to break out of the infinite loop, you can use abreakstatement, e.g.