The program I'm currently writing uses a linked list. When the the program first starts, the current list needs to print 1 element with the value '0'. This happens before the user has added anything to it. I tried editing my current Print method to accomplish this, but it's not printing anything out. The print method still works after I manually enter in elements. Just can't get the initial print to work. Here's what I tried.
void LList::Print(){
//PreConditions: The native object LList is valid
//PostConditions: The native object LList is unchanged and its elements
// have been displayed
listnode * temp;
if (head != NULL)
temp = head;
else{
temp = new listnode;
temp->data = 0;
temp->next = NULL;
head = temp;
}
while (temp != NULL){
cout << temp->data;
temp = temp->next;
}
}
//PostConditions: The native object LList is unchanged and its elements
// have been displayed
This condition tells us to mark the function const (marked bold)
So, if there is no element in there you don't want a Node to be created in the List, right?
in that case, you should remove the head = temp; after creating a new listnode
also, you can only just print "0" and return if you don't want to add an empty element :b
i still don't understand what you mean by print 1 element with value 0 if the List is empty
void LList::Print() const
{
//PreConditions: The native object LList is valid
//PostConditions: The native object LList is unchanged and its elements
// have been displayed
if(head == NULL)
{
std::cout << '0' << std::endl; // print 0, but not not modifying LList
return;
}
listnode* temp = head;
while (temp != NULL)
{
cout << temp->data;
temp = temp->next;
}
}
Thanks. I wasn't really thinking about the post conditions when attempting to solve this.
As to your question, it doesn't necessary need to be a listnode. When the user hasn't entered anything yet, I need to print "Current List: 0". So, your solution works. Thanks