你能在 JAVA 中操作堆栈吗 [英] can you manipulate a stack in JAVA

查看:64
本文介绍了你能在 JAVA 中操作堆栈吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我给了一个带有字符串行的 txt 文件,我必须在其中取前 50 行并以相反的顺序打印它们(澄清:该行没有改变,但顺序改变了......第 50 行变成第 1、第 49 行变为第 2 行,依此类推……)然后再重复接下来的 50 行,直到所有行都反转.

lets say im given a txt file with lines of strings, where i have to take the first 50 lines and print them in reverse order(to clarify: the line does not change, but the order changes...50th line becomes 1st, 49th becomes 2nd, etc...) and then again for the next 50 lines until all lines are reversed.

到目前为止,我有多个 for 循环一次通过 50 行并反转它们.但是有没有更有效的方法来做到这一点?我在考虑堆栈,但是我不知道如何操作堆栈中的元素而不是 pop() 和 push().

So far i have multiple for loops going through 50 lines at a time and reversing them. But is there a more efficient way to do this? i was thinking of stacks, however i dont know how to manipulate the elements in a stack over than pop() and push().

这是我目前得到的

    for(int x = 49; x>=0; x--){ 
        System.out.println(s.get(x));
    }

    for(int x = 149; x>=100; x--){ 
        System.out.println(s.get(x));
    }
    ...
    ...

推荐答案

一种算法

堆栈文档:http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html

Stack<String> stk = new Stack<String>
while not EOF
    for 50 lines
        stk.push(line)
    while(!stk.empty())
        print stk.pop()

这篇关于你能在 JAVA 中操作堆栈吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆