Hi, everyone i'm having some problems with an assignment. we are supposed to create a program using structured linked list, that uses one global variable to represent pointer to head, two functions input and print, both are to use "while" loop.
i'm having trouble kicking it out of the while loop. at this point I'm pretty much lost any help is appreciated.
lines 48-49: If the user enters 1, you're fine since you continue to the top of the loop and the newly allocated node is modified. However, if the user enters 0, you're left with an empty extraneous node.
You never modify head to point to the new node as you create nodes.
Line 15: head is an uninitialized null pointer.
Line 24: You pass an uninitialized null pointer to your print function resulting in undefined behavior (probably a crash) printList() not printing the list.
Edit: Corrected uninitialized pointer for null pointer.
void inputfn()
{ int num;
node *nodePtr;
nodePtr = new node;
while(nodePtr != NULL)
{ cout << "Please enter the tracking number: " <<endl;
cin >> nodePtr->tracking;
cout << "Please enter the Type of Animal: " <<endl;
cin >> nodePtr->animal;
cout << "Please enter the Daily Boarding Charge: "<<endl;
cin >> nodePtr->charge;
nodePtr->Next = head; // chain existing list (if any) to current node
head = nodePtr; // Set head to current node
cout<<"To continue inputting data enter '1' or '0' to print list"<<endl;
cin >> num;
if (num == 0) // You were using assignment operator (=), not the equality operator (==)
{ nodePtr = NULL;
continue; // return to top of loop
}
nodePtr = new node; // Now we can allocate new node for next iteration
}
}
void
inputfn()
{
int num=1;
while (num == 1) {
node *nodePtr = new node;
cout << "Please enter the tracking number: " << endl;
cin >> nodePtr->tracking;
cout << "Please enter the Type of Animal: " << endl;
cin >> nodePtr->animal;
cout << "Please enter the Daily Boarding Charge: " << endl;
cin >> nodePtr->charge;
nodePtr->Next = head; // chain existing list (if any) to current node
head = nodePtr; // Set head to current node
cout << "To continue inputting data enter '1' or '0' to print list" << endl;
cin >> num;
}
}
It would be better to use a do-while loop but the OP specifically says while loops.
The point still stands that the OP never modifies head, therefore, printList() will print only the header and will not print the list since printList() is passed a null pointer.