我想打印这样一个链表:
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;
}
- 只遍历一次List
- for 循环而不是 while。
- 速度并不重要,因为您的列表应该很小(除非您有非常非常宽的屏幕或非常小的字体),因为您希望列表的内容能够整齐地适合输出窗口的 1 行。<
关于c++ - 我如何优化此代码以这种格式打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35714754/