lundi 29 février 2016

How can I optimize this code to print in this format?

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.

Aucun commentaire:

Enregistrer un commentaire