如何优化此代码以此格式打印?

时间:2016-03-01 04:34:58

标签: c++ performance c++11 optimization time-complexity

我想打印一个这样的链接列表:

0       1       2       3       4
12      24      36      85      48

我目前的代码是

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;
}

我很确定还有另一种方法可以做到更简单,更快捷。我想减少这段代码的冗余。

我正在显示计数器以帮助用户添加或删除数字。

3 个答案:

答案 0 :(得分:2)

$q= $_GET[q];
  • 只有一个List遍历
  • for-loop而不是while。
  • 速度无关紧要,因为您的列表应该很小(除非您有非常宽的屏幕或微小的字体),因为您希望列表的内容整齐地放入输出窗口的1行。

答案 1 :(得分:1)

这实际上取决于你的意思&#34;优化&#34;。由于缓存局部性较差,链接列表对于遍历本质上是次优的。更不理想的是将整数数据转换为文本并写入流。

因此,我只能得出结论,您希望减少代码冗余并将其视为优化,即使它以牺牲执行时间为代价。一种可能的解决方案是接受应用于每个元素的函数:

void LinkedList::forEach( std::function<void (node*)> fn )
{
    for( node *curr = head; curr != NULL; curr = curr->next )
    {
        fn( curr );
    }
}

现在您可以使用它来打印节点数据或其他内容:

void LinkedList::printList()
{
    int count = 0;
    forEach( [&count]( node * ) { cout << count++ << "\t"; } );
    cout << endl;
    forEach( []( node *n ) { cout << n->data << "\t"; } );
    cout << endl;
}

答案 2 :(得分:0)

您可以尝试使用ANSI转义码来移动打印输出位置,并在一个循环中完成所有操作。 Emoji encoding