I want to print a linked list like this:
0 1 2 3 4
12 24 36 85 48
My current code is
void LinkedList::printList()
{
curr = head; //store head in curr to irerate
int count = 0; //counter to help uer manipulate list
while (curr != NULL) //traverse whole list
{
cout << count++ <<"\t"; //print index
curr = curr->next; //move to next
}
curr = head; //make current head again
cout << endl;//go to next line
while (curr != NULL) //traverse whole list
{
cout << curr->data << "\t"; //print data
curr = curr->next; //move to next
}
cout << endl;
}
I am pretty sure there's another way to do this is a simpler and faster way. I want to reduce the redundancy on this code.
I am showing the counter to help user add or delete numbers.
It really depends on what you mean by "optimize". Linked lists are inherently suboptimal for traversal because of poor cache locality. Even less optimal is converting integer data to text and writing to a stream.
So I can only conclude that you wish to reduce code redundancy and consider that to be an optimization, even if it's at the expense of execution time. One possible solution is to accept a function that is applied to each element:
void LinkedList::forEach( std::function<void (node*)> fn )
{
for( node *curr = head; curr != NULL; curr = curr->next )
{
fn( curr );
}
}
And now you can use this to print node data or other stuff:
void LinkedList::printList()
{
int count = 0;
forEach( [&count]( node * ) { cout << count++ << "\t"; } );
cout << endl;
forEach( []( node *n ) { cout << n->data << "\t"; } );
cout << endl;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments