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

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

本文关键字:格式 式打印 代码 何优化 优化      更新时间:2023-10-16

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

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

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

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

#include <sstream>
void LinkedList::printList(std::ostream& os = std::cout) {
    size_t counter = 0;
    std::ostringstream indx;
    std::ostringstream value;
    for( ListNode *current = head; current != NULL; current = current->next ) {
        indx << counter++ << "t";
        value << current->data << "t";
    }
    os << indx.str().c_str() << std::endl << value.str().c_str() << std::endl;
}
  • 只有一个列表遍历
  • for 循环而不是 while。
  • 速度并不重要,因为您的列表应该很小(除非您有一个非常非常宽的屏幕或很小的字体),因为您希望列表的内容整齐地适合输出窗口的 1 行。

这实际上取决于您所说的"优化"是什么意思。 链表本质上是遍历的次优选择,因为缓存局部性较差。 更不理想的是将整数数据转换为文本并写入流。

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

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

您可以尝试使用 ANSI 转义码来移动打印输出位置,并在一个循环中完成所有操作。http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x361.html