读取输入流的 N 行并以相反的顺序打印而不使用数组或列表类型结构?
使用 BufferedReader 的 readLine() 方法,可以在不使用列表或数组的情况下以相反的顺序打印流的前 N 行吗?
Using the readLine()
method of BufferedReader
, can you print the first N lines of a stream in reverse order without using a list or an array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我认为你可以通过递归来做到这一点,例如:
I think you can do it through recursion with something like:
这里你有另一种选择,基于 BufferedReader & StringBuilder 操作。就所需的计算机资源而言更易于管理。
Here you have another alternative, based on BufferedReader & StringBuilder manipulations. More manageable in terms of computer resources needed.
怎样用递归来颠倒顺序呢?
伪代码:
How about recursion to reverse the order?
Pseudo code:
好问题。这里您有一种基于协调线程的解决方案。尽管它占用大量资源(1 个线程/缓冲区行),但它可以在给定的限制内解决您的问题。我很好奇看到其他解决方案。
Nice question. Here you have one solution based on coordinated threads. Although it's heavy on resources (1 thread/line of the buffer) it solves your problem within the given constrains. I'm curious to see other solutions.
它还需要隐式数据结构,但您可以生成线程,按顺序运行它们,并使每个线程读取一行并等待较短的时间。结果将是:最后一个线程将首先运行,第一个线程将最后运行,每个线程都打印其行。 (它们之间的间隔必须足够大,以确保大的“安全裕度”)
我不知道如何(如果有的话)在没有显式/隐式数据存储的情况下完成这一点。
it will also require implicit data structures, but you can spawn threads, run them inorder, and make each thread read a line and wait a decreasing amount of time. the result will be: the last thread will run first, and the first one will run last, each one printing its line. (the interval between them will have to be large enough to ensure large "safety margins")
I have no idea how, if any, that can be done with no explicit/implicit data storage.
将您读取的每一行添加到一个字符串中,然后打印该字符串。如果您读完了所有行,只需打印您所拥有的内容即可。
或者,如果您确定拥有的行数,并且不希望使用字符串:
Prepend each line you read to a string, and print the string. If you run out of lines to read, you just print what you have.
Alternatively, if you are certain of the number of lines you have, and you do not wish to use a string: