I am trying to write a program that generates a number of nodes equivalent to a valid integer entered by the user. That in itself isn't hard... the tricky part is they want to have me read the list of nodes forward and backward using the null to terminate in each direction.
So my generated node must be in the format of [null][value][null]
Where value increments by 1 for each value entered by the user.
Can anyone see i'm getting close in my attempt, or do I need to try a different approach??
#include <iostream>
#include<limits>
usingnamespace std;
int main()
{
struct listrec
{
struct listrec *prev;
float nbr;
struct listrec *next;
};
listrec *head, *tail;
float userin;
cout << " Please enter the number of nodes you would like to create "<< endl;
cin>>userin;
while(!(cin >> userin) || userin < 0)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input, the input must be zero or greater and not a letter" << endl;
}
head = null; current = null;
for(int i =1; i < userin+1; i++)
{
if (head==null)
{
head = new node;
head -> nbr = i;
head -> next = null;
current = head;
}
else
{
current -> next = new node;
current = current -> next;
current -> tail = null; //will this work
current -> nbr = i;
current -> next = null;
}
}
}
read the list of nodes forward and backward using the null to terminate in each direction
a relatively straight-forward way to do this would be to overload the listrec() ctor so that prev and next are initialized to nullptr (use nullptr instead of null, which doesn't compile, or even NULL) and then at the time of node insertions you can assign to prev and next as required, so prev of head and next of tail are usually not assigned to and therefore left as nullptr in each case
Can anyone see i'm getting close in my attempt
yes, you seem to be on the right lines overall. here's a link to a recent forum discussion on doubly linked list that could give you some ideas including the overloaded ctor mentioned above: http://www.cplusplus.com/forum/beginner/210745/#msg988500