can you manipulate a stack in JAVA

依然范特西╮ 提交于 2020-02-03 02:14:08

问题


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.

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().

this is what i got so far

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

回答1:


An algorithm

Stack documentation: 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()



回答2:


A LinkedList implements the Deque interface, which seems to be exactly what you need.



来源:https://stackoverflow.com/questions/32685123/can-you-manipulate-a-stack-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!